繁体   English   中英

iOS(Swift)应用程序在JSON解析时崩溃

[英]iOS (Swift) application is crashing on JSON parsing

我在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响应字符串:可选(“ {\\ n \\” ConsumerID \\“:\\” w4wccKqF9qN0biUM3HGvGMDK27Q2 \\“,\\ n \\” resultCount \\“:10,\\ n \\” resultList \\“:[\\ n \\” Thai Basil \\“, \\ n \\“泰国菠萝咖喱\\”,\\ n \\“泰国生菜包裹”,\\ n \\“泰国绿咖喱\\”,\\ n \\“泰国红咖喱\\”,\\ n \\“泰国四季豆虾\\” ,\\ n \\\\“泰国罗勒茄子\\”,\\ n \\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\“泰国泰式辣椒酱\\\\\\\\\\”,\\“泰国鸡蛋卷”,1.泰国鸡蛋卷(3)\\“ \\ n] \\ n} \\ n”)

崩溃日志:

捕获:错误域= NSCocoaErrorDomain代码= 3840“字符305周围的格式不正确的数组。” UserInfo = {NSDebugDescription =字符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: "\\"")

根据您的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)"
   ]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM