YAJL - JSON on iOS/iPhone
In my iPhone app, I am trying to use the JSON library (YAJL) to create a JSON string that looks like the following format:
{"user":
{"name":"Jon", "username":"jon22", "password":"passw@rd", "email":"jon22@example.com"}
}
But I can't figure out the YAJL methods to create this.
I have tried the following:
NSArray *params = [NSArray arrayWithObjects:@"Jon", @"jon22", @"passw@rd", @"jon22@gmail.com", nil];
NSArray *keys = [NSArray arrayWithObjects:@"name", @"username", @"password", @"email", nil];
NSDictionary开发者_Python百科 *userDictionary = [NSDictionary dictionaryWithObjects:params forKeys:keys];
NSString *JSONString = [userDictionary yajl_JSONString];
However, the returned string is not wrapped in the outside "user". How can I use YAJL to create this json string? Does anyone have experience with this???
Many thanks, Brett
I don't use YAJL, but SBJSON, which is the one Apple uses in iOS too...
Anyway, the library is behaving correctly: you're not creating an "user" dictionary!
You need to do something like:
NSDictionary *serialize = [NSDictionary dictionaryWithObject:userDictionary forKey:@"user"];
And then "JSON-ize" this one.
This is because when you call -yajl_JSONString
on userDictionary, you are using userDictionary as your "root object". If you want to wrap this inside another dictionary, you need to explicitly do so.
I highly recommend that you check out JSONKit https://github.com/johnezang/JSONKit I have used numerous JSON parsers and have found it to be the easiest.
Also the documentation is awesome.
精彩评论