Generate JSON string from NSDictionary in iOS Generate JSON string from NSDictionary in iOS ios ios

Generate JSON string from NSDictionary in iOS


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];}


Here are categories for NSArray and NSDictionary to make this super-easy. I've added an option for pretty-print (newlines and tabs to make easier to read).

@interface NSDictionary (BVJSONString)-(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint;@end

.

@implementation NSDictionary (BVJSONString)  -(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint {     NSError *error;     NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self                                                   options:(NSJSONWritingOptions)    (prettyPrint ? NSJSONWritingPrettyPrinted : 0)                                                     error:&error];     if (! jsonData) {        NSLog(@"%s: error: %@", __func__, error.localizedDescription);        return @"{}";     } else {        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];     }  }@end

.

@interface NSArray (BVJSONString)- (NSString *)bv_jsonStringWithPrettyPrint:(BOOL)prettyPrint;@end

.

@implementation NSArray (BVJSONString)-(NSString*) bv_jsonStringWithPrettyPrint:(BOOL) prettyPrint {    NSError *error;    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:self                                                       options:(NSJSONWritingOptions) (prettyPrint ? NSJSONWritingPrettyPrinted : 0)                                                         error:&error];    if (! jsonData) {        NSLog(@"%s: error: %@", __func__, error.localizedDescription);        return @"[]";    } else {        return [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];    }}@end


To convert a NSDictionary to a NSString:

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