Generate JSON string from NSDictionary in iOS

ChandraSekhar picture ChandraSekhar · Jun 16, 2011 · Viewed 292.3k times · Source

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 on this?

Answer

Guillaume picture Guillaume · Jan 26, 2012

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
                                                     error:&error];

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