how to create json in objective-c

meth picture meth · Aug 13, 2012 · Viewed 45.5k times · Source
NSData* jsonDataToSendTheServer;

NSDictionary *setUser = [NSDictionary
            dictionaryWithObjectsAndKeys:[@"u" stringByAppendingString:my.id],@"id",
                                        @"GET_USER_INFO",@"command",
                                        @"",@"value",
                                        nil];

 NSLog(@"%@", jsonDataToSendTheServer);

Here is my code. When I run above code I get this print

<7b226964 223a2275 35383738 37373334 31222c22 636f6d6d 616e6422 3a224745 545f5553 45525f49 4e464f22 2c227661 6c756522 3a22227d>

I don't have any idea whether I can created a json or not.

How can I fix this?

Answer

bryanmac picture bryanmac · Aug 13, 2012

You're missing this line to convert it to json

NSData* jsonData = [NSJSONSerialization dataWithJSONObject:setUser 
                   options:NSJSONWritingPrettyPrinted error:&error];

Here's a tutorial on NSJSONSerialization that may help you: http://www.raywenderlich.com/5492/working-with-json-in-ios-5

After that, you can convert the NSData to an NSString to print:

Convert UTF-8 encoded NSData to NSString