How can you deserialize an escaped JSON string with NSJSONSerialization? How can you deserialize an escaped JSON string with NSJSONSerialization? json json

How can you deserialize an escaped JSON string with NSJSONSerialization?


If you have nested JSON, then just call JSONObjectWithData twice:

NSString *string =  @"\"{ \\\"name\\\" : \\\"Bob\\\", \\\"age\\\" : 21 }\"";// --> the string// "{ \"name\" : \"Bob\", \"age\" : 21 }"NSError *error;NSString *outerJson = [NSJSONSerialization JSONObjectWithData:[string dataUsingEncoding:NSUTF8StringEncoding]                              options:NSJSONReadingAllowFragments error:&error];// --> the string//  { "name" : "Bob", "age" : 21 }NSDictionary *innerJson = [NSJSONSerialization JSONObjectWithData:[outerJson dataUsingEncoding:NSUTF8StringEncoding]                              options:0 error:&error];// --> the dictionary// { age = 21; name = Bob; }


Convert the string to data:

NSString *string = @"{ \"name\" : \"Bob\", \"age\" : 21 }";NSData *data = [string dataUsingEncoding:NSUTF8StringEncoding];NSError *error;id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:&error];


Just cut off the leading and trailing quotes and then replace all \"s with ":

NSString *sub = [original substringWithRange:(NSRange){ 1, original.length - 2 }];NSString *unescaped = [sub stringByReplacingOccurrencesOfString:@"\\\" withString:@"\"];