为什么JSONSerialization在JSON字符串中省略了转发斜杠?

时间:2018-03-15 20:30:36

标签: swift nsjsonserialization

来自MockURL200Session的传入JSON产生的值为2017-11-25 09:47:18 Etc/GMT

class MockURL200Session: URLSessionProtocol {
    var nextDataTask = MockURLSessionDataTask()
    var nextData: Data?
    var nextError: Error?

    func httpURLResponse(request: NSURLRequest) -> URLResponse {
        return HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: "HTTP/1.1", headerFields: nil)!
    }

    func dataTask(with request: NSURLRequest, completionHandler: @escaping DataTaskResult) -> URLSessionDataTaskProtocol {
        let json = ["expires_date": "2017-11-25 09:47:18 Etc/GMT"]
        nextData = try! JSONSerialization.data(withJSONObject: json, options: [])
        completionHandler(nextData, httpURLResponse(request: request), nextError)
        return nextDataTask as URLSessionDataTaskProtocol
    }
}

但是,一旦它到达客户端,正斜杠就会消失并变为2017-11-25 09:47:18 Etc GMT

self.httpClient.post(url: url) { (data, response, error) in
   let json = try! JSONSerialization.jsonObject(with: data!, options: []) as! Dictionary<String, Any>
}

我该如何预防或逃避它?

1 个答案:

答案 0 :(得分:1)

dataTask()中,您对JSONSerialization.data()的调用在解码时会转发正斜杠。从nextData返回之前,您可以在dataTask()中看到它。在返回客户端的某个地方,\/组合正在被移除。当你尝试解码服务器响应时我会猜测它。既然你知道发生了什么,你就可以找到问题的其余部分的解决方案here,或者如果没有,谷歌就像&#34; swift jsonserialization escape slash&#34;。祝你好运。