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

后端 未结 3 404
挽巷
挽巷 2020-12-10 05:01

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

3条回答
  •  暖寄归人
    2020-12-10 06:06

    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
        }
    }
    

提交回复
热议问题