我在iOS (Swift)应用程序中调用rest,并在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响应字符串:可选(“{ \n \”ConsumerID\:\“w4wccKqF9qN0biUM3HvGMDK27Q2\”,\n \"resultCount\":10,\n \"resultList\":\n \“泰式Basil\",\n \”泰式菠萝咖喱\“,\n \”泰国生菜卷\“,\n \”泰国绿色咖喱“,\n \”泰国红咖喱\“,\n\”泰豆串虾\“,“泰式巴兹尔茄子\n \\”泰国巴兹尔醉面\\“帕德·基·毛\\”,\n \\“泰国智利鱼”,\n \"1.泰国鸡蛋卷(3)\“\”n}“)
崩溃日志:
捕获: Error Domain=NSCocoaErrorDomain Code=3840“字符305左右的错误数组。UserInfo={NSDebugDescription=Badly在字符305左右形成数组。}
发布于 2019-07-23 07:28:24
我想是因为这行代码:
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: "\\"")发布于 2019-07-23 07:35:58
根据您的json响应日志,后端似乎正在返回无效的json响应。下面应该是正确的json响应。
{
"ConsumerID":"w4wccKqF9qN0biUM3HGvGMDK27Q2",
"resultCount":10,
"resultList":[
"Thai Basil",
"Thai Pineapple Curry",
"Thai Lettuce Wrap",
"Thai Green Curry",
"Thai Red Curry",
"Thai String Bean Shrimp",
"Thai Basil Eggplant",
"Thai Basil Drunken Noodle \"Pad Kee Mao\"",
"Thai Chili Fish",
"1. Thai Egg Roll(3)"
]
}https://stackoverflow.com/questions/57158414
复制相似问题