Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to create json in objective-c

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?

like image 447
meth Avatar asked Aug 13 '12 10:08

meth


2 Answers

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

like image 105
bryanmac Avatar answered Sep 30 '22 17:09

bryanmac


You can try following to create JSON:

NSArray *objects=[[NSArray alloc]initWithObjects:objects here,nil];
NSArray *keys=[[NSArray alloc]initWithObjects:corresponding keys of objects,nil];
NSDictionary *dict=[NSDictionary dictionaryWithObjects:objects forKeys:keys];
NSData *jsonData=[NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];

this worked perfectly in my case

like image 41
V-Xtreme Avatar answered Sep 30 '22 18:09

V-Xtreme