Note that there are some explanatory texts on larger screens.

plurals
  1. PONSJSONSerialization serialization of a string containing forward slashes / and HTML is escaped incorrectly
    primarykey
    data
    text
    <p>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.</p> <p>Example... I have a string which contains some basic HTML text:</p> <pre><code>NSString *str = @"&lt;html&gt;&lt;body&gt;&lt;p&gt;Samples / Text&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;"; </code></pre> <p>The desired outcome is JSON with HTML as the value:</p> <pre><code>{ "Title":"My Title", "Instructions":"&lt;html&gt;&lt;body&gt;&lt;p&gt;Samples / Text&lt;/p&gt;&lt;/body&gt;&lt;/html&gt;" } </code></pre> <p>I'm using the standard technique to convert an NSDictionary to a NSString containing JSON:</p> <pre><code>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:&amp;err]; NSString *resultingString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding]; NSLog(@"%@", resultingString); </code></pre> <p>The JSON produced by this method is valid, however the HTML has all forward slashes escaped:</p> <pre><code>{ "Title":"My Title", "Instructions":"&lt;html&gt;&lt;body&gt;&lt;p&gt;Samples \/ Text&lt;\/p&gt;&lt;\/body&gt;&lt;\/html&gt;" } </code></pre> <p>This creates invalid HTML in the instructions JSON string.</p> <p>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.</p> <p>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: <a href="https://stackoverflow.com/questions/3413878/escaping-json-string-with-a-forward-slash">escaping json string with a forward slash?</a> and also <a href="https://stackoverflow.com/questions/1580647/json-why-are-forward-slashes-escaped">JSON: why are forward slashes escaped?</a>. 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.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload