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

标签 ios swift string crash

我在 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/

相关文章:

ios - 即使创建了 Swift Bridging Header 文件,也无法在 Objective C 中引用 Swift 类

ios - TableViewCell 问题上的 MapView

c# - 如何在打印之前预先测量字符串?

ios - AudioUnit inputCallback with AudioUnitRender -> audioBufferList.mBuffers[0].mDataByteSize != inNumberFrames 之间不匹配

ios - 您可以在 iOS 中使用任何 SQLITE3 数据库吗,或者是否有您应该匹配的特殊格式?

swift - Swift 3 中 var 的默认值

ios - 如何阻止重用单元格模仿其他单元格的样式更改?

ios - 谓词的核心数据提取请求错误

android - 在不使用淡入淡出动画的情况下调用 TextSwitcher 的 SetText

Android:strings.xml 中的字符串不是字符串?