开发者

Objective-c SBJSONWriter convert array of dictionaries to JSON

I'm having some trouble with SBJsonWriter at the moment.

I need to send a request that contains a json object of name/value pairs. e.g.

[{%22uid%22:1,%22version%22:1}]

I can't figure out how to do this in Obj-C with the SBJ开发者_运维技巧son Writer framework.

For each pair I have tried to construct a dictionary then add the dictionary to an array. This results in an array containing many dictionaries, each containing one name/value pair.

Any idea on how a fix for this or is it possible?

Thanks in advance


To produce an Objective-C structure equivalent to the above JSON you should do this:

NSArray* json = [NSArray arrayWithObject: [NSDictionary dictionaryWithObjectsAndKeys: 
                                               [NSNumber numberWithInt: 1], @"uid",
                                               [NSNumber numberWithInt: 1], @"version",
                                               nil]];


Check my answer to the '' SBJsonWriter Nested NSDictionary '' question. it illustrates how to properly use SBJsonWriter.

It includes error check and some pieces of advise about SBJsonWriter behaviour with NSDate, float, etc..

Excerpt:

NSDictionary* aNestedObject = [NSDictionary dictionaryWithObjectsAndKeys:
                                      @"nestedStringValue", @"aStringInNestedObject",
                                      [NSNumber numberWithInt:1], @"aNumberInNestedObject",
                                 nil];

NSArray * aJSonArray = [[NSArray alloc] initWithObjects: @"arrayItem1", @"arrayItem2", @"arrayItem3", nil];

NSDictionary * jsonTestDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
                                     @"stringValue", @"aString",
                                     [NSNumber numberWithInt:1], @"aNumber",
                                     [NSNumber numberWithFloat:1.2345f], @"aFloat",
                                     [[NSDate date] description], @"aDate",
                                     aNestedObject, @"nestedObject",
                                     aJSonArray, @"aJSonArray",
                                     nil];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜