I am trying to convert some simple HTML into a string value in a JSON object and I'm having trouble getting the string encoding to not escape the string in NSJSONSerialization.
Example... I have a string which contains some basic HTML text:
NSString *str = @"<html><body><p>Samples / Text</p></body></html>";
The desired outcome is JSON with HTML as the value:
{
"Title":"My Title",
"Instructions":"<html><body><p>Samples / Text</p></body></html>"
}
I'm using the standard technique to convert an NSDictionary to a NSString containing JSON:
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
[dict setObject:str forKey:@"Instructions"];
[dict setObject:@"My Title" forKey:@"Title"];
NSError *err;
NSData *data = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&err];
NSString *resultingString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
NSLog(@"%@", resultingString);
The JSON produced by this method is valid, however the HTML has all forward slashes escaped:
{
"Title":"My Title",
"Instructions":"<html><body><p>Samples \/ Text<\/p><\/body><\/html>"
}
This creates invalid HTML in the instructions JSON string.
I'd like to stick with NSJSONSerialization since we're using that everywhere else in our framework and I've been burned before switching to non-Apple libraries as they get desupported. I've tried many different string encodings and all of them escape the angle brackets.
Apparently \/ is a valid representation in JavaScript for the / characters, which is why forward slash is escaped (even the StackOverflow text editor escaped it). See: escaping json string with a forward slash? and also JSON: why are forward slashes escaped?. I just don't want it to do that and there doesn't seem to be a way to stop iOS from escaping forward slashes in string values when serializing.