我在 iOS (Swift) 应用程序中调用 rest api 并在 JSON 中获取响应。但是当我试图解析它时,应用程序在这条线上崩溃了
let myData = jsonString.data(using: .utf8)
代码:
print("JSON Response String: \(String.init(data: data!, encoding: .utf8))")
var jsonString:String = String.init(data: data!, encoding: .utf8)!
jsonString = jsonString.replacingOccurrences(of: "\\", with: "")
let myData = jsonString.data(using: .utf8)
let dict:[String:Any] = (try JSONSerialization.jsonObject(with: myData!, options: []) as? [String:Any])!
print("JSON Response Dictionary: \(dict)")
崩溃日志
JSON Response String: Optional("{\n \"ConsumerID\": \"w4wccKqF9qN0biUM3HGvGMDK27Q2\", \n \"resultCount\": 10, \n \"resultList\": [\n \"Thai Basil\", \n \"Thai Pineapple Curry\", \n \"Thai Lettuce Wrap\", \n \"Thai Green Curry\", \n \"Thai Red Curry\", \n \"Thai String Bean Shrimp\", \n \"Thai Basil Eggplant\", \n \"Thai Basil Drunken Noodle \\"Pad Kee Mao\\"\", \n \"Thai Chili Fish\", \n \"1. Thai Egg Roll(3)\"\n ]\n}\n")
崩溃日志:
caught: Error Domain=NSCocoaErrorDomain Code=3840 "Badly formed array around character 305." UserInfo={NSDebugDescription=Badly formed array around character 305.}
最佳答案
我认为这是因为这行代码:
jsonString = jsonString.replacingOccurrences(of: "\\", with: "")
您必须相应地使用正确的转义字符:
以下字符在 JSON 中保留,必须正确转义才能在字符串中使用:
Backspace is replaced with \b
Form feed is replaced with \f
Newline is replaced with \n
Carriage return is replaced with \r
Tab is replaced with \t
Double quote is replaced with \"
Backslash is replaced with \\
所以正确的方法是:
jsonString = jsonString.replacingOccurrences(of: "\\", with: "\\"")
关于iOS (Swift) 应用程序在 JSON 解析时崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57158414/