NSJSONSerialization serialization of a string containing forward slashes / and HTML is escaped incorrectly

北城余情 提交于 2019-11-28 10:05:32
Jessedc

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.

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
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!