Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Generate JSON string from NSDictionary in iOS

I have a dictionary I need to generate a JSON string by using dictionary. Is it possible to convert it? Can you guys please help with this?

2 Answers

Apple added a JSON parser and serializer in iOS 5.0 and Mac OS X 10.7. See NSJSONSerialization.

To generate a JSON string from a NSDictionary or NSArray, you do not need to import any third party framework anymore.

Here is how to do it:

NSError error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dictionaryOrArrayToOutput
options:NSJSONWritingPrettyPrinted // Pass 0 if you don't care about the readability of the generated string

if (! jsonData) {
NSLog(@"Got an error: %@", error);
} else {
jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
To convert a NSDictionary to a NSString:

NSError  err;
NSData * jsonData = [NSJSONSerialization dataWithJSONObject:myDictionary options:0 error:&err];
myString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];

Login / Signup to Answer the Question.