我之前发过一篇关于相关问题的文章,但我认为我要发一个新帖子。
我正在向IOS发送一个返回JSON的应用服务请求。返回的JSON格式如下:
"{\"raw\":\"schedule for John in New York on Monday\",\"location\":\"new york\",\"date\":\"6/26/2017 12:00:00 AM\",\"name\":\"john\",\"errorResponse\":null,\"stripTest\":\" for john in new york on monday \"}"
但是,当我打印String(data:data,encoding:String.Encoding.utf8),其中data是请求的返回值时,我得到:
`可选(" \" {\\" raw \\":\\"约翰在纽约周一的日程安排\\" ,\\" location \\":\\" new york \\",\\" date \\":\\" 6/26/2017 12:00:00 AM \\",\\"名称\\":\\" john \\",\\&# 34; errorResponse \\":null,\\" stripTest \\":\\"对于星期一的纽约约翰\\"} \&#34 ;")'
我假设当我转换"数据"到一个字符串。有什么方法可以避免这种情况吗?
结果字符串没用,因为我无法将其转换为字典来访问数据。我尝试过直接从数据转换为字典,但这似乎也不起作用(结果字典有0个键/值对)。
一旦应用程序存储了返回值,可能会添加额外的字符吗?
let json: [String: String] = ["raw": self.result]
let jsonData = try? JSONSerialization.data(withJSONObject: json)
var postRequest = URLRequest(url: URL(string: "blahblah.com/")!)
postRequest.httpMethod = "POST"
postRequest.addValue("application/json", forHTTPHeaderField: "Content-Type")
postRequest.addValue("application/json", forHTTPHeaderField: "Accept")
//insert JSON data to the new request
postRequest.httpBody = jsonData
let task = URLSession.shared.dataTask(with: postRequest) { data, response, error in
guard let data = data, error == nil else {
print(error?.localizedDescription ?? "NoData")
return
}
let jsonString = String(data: data, encoding: String.Encoding.utf8)
print(jsonString)
let jsonData = jsonString?.data(using: String.Encoding.utf8)!
if let jsonObj = try? JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as? [String : AnyObject]
}
task.resume()