如何在objective-c中创建json

met*_*eth 17 json objective-c ios nsjsonserialization

NSData* jsonDataToSendTheServer;

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

 NSLog(@"%@", jsonDataToSendTheServer);
Run Code Online (Sandbox Code Playgroud)

这是我的代码.当我运行上面的代码时,我得到了这个打印

<7b226964 223a2275 35383738 37373334 31222c22 636f6d6d 616e6422 3a224745 545f5553 45525f49 4e464f22 2c227661 6c756522 3a22227d>
Run Code Online (Sandbox Code Playgroud)

我不知道我是否可以创建一个json.

我怎样才能解决这个问题?

bry*_*mac 32

你错过了这一行将它转换为json

NSData* jsonData = [NSJSONSerialization dataWithJSONObject:setUser 
                   options:NSJSONWritingPrettyPrinted error:&error];
Run Code Online (Sandbox Code Playgroud)

这是一个关于NSJSONSerialization的教程,它可以帮到你:http://www.raywenderlich.com/5492/working-with-json-in-ios-5

之后,您可以将NSData转换为NSString进行打印:

将UTF-8编码的NSData转换为NSString


V-X*_*eme 7

您可以尝试以下来创建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];
Run Code Online (Sandbox Code Playgroud)

在我的情况下,这完美地运作