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 NSJSONSerializat
I believeNSJSONSerialization
is behaving as designed in regards to encoding HTML.
If you look at some questions (1, 2) on encoding HTML in JSON you'll see the answers always mention escaping the forward slashes.
JSON doesn't require forward slashes to be escaped, but HTML doesn't allow a javascript string to contain </
as it can be confused with the end of the <SCRIPT>
tag.
See the answers here, here and most directly the w3.org HTML4 Appendix which states in B.3.2 Specifying non-HTML data
ILLEGAL EXAMPLE:
The following script data incorrectly contains a "</" sequence (as part of "</EM>") before the SCRIPT end tag:
<SCRIPT type="text/javascript">
document.write ("<EM>This won't work</EM>")
</SCRIPT>
Although this behaviour may cause issues for you NSJSONSerialisation
is just playing by the age old rules of encoding HTML data for use in <SCRIPT>
tags.
iOS 13 only:
If you're not worried about producing invalid HTML sequences (as described in this answer), you can disable forward-slash escaping by passing the option NSJSONWritingWithoutEscapingSlashes
to the serializer.
Example:
jsonData = [NSJSONSerialization dataWithJSONObject:batchUpdates
options:NSJSONWritingWithoutEscapingSlashes
error:nil];
Here's my subclass of AFJSONRequestSerializer
to remove \
before /
symbols in resulting JSON; handy if you use AFNetworking
class SanitizedAFJSONRequestSerializer: AFJSONRequestSerializer
{
override func requestBySerializingRequest(request: NSURLRequest!, withParameters parameters: AnyObject!, error: NSErrorPointer) -> NSURLRequest!
{
var request = super.requestBySerializingRequest(request, withParameters: parameters, error: error)
if let jsonData = request.HTTPBody
{
if let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as? String
{
let sanitizedString = jsonString.stringByReplacingOccurrencesOfString("\\/", withString: "/", options: NSStringCompareOptions.CaseInsensitiveSearch, range:nil) as NSString
println("sanitized json string: \(sanitizedString)")
var mutableRequest = request.mutableCopy() as! NSMutableURLRequest
mutableRequest.HTTPBody = sanitizedString.dataUsingEncoding(NSUTF8StringEncoding)
request = mutableRequest
}
}
return request
}
}