我在我的 swift 项目中使用本地 JSON。我需要提取数组中的数据。我遇到意外崩溃。
我的 JSON 是:
{
cueca = (
{
agentName = "Sant";
applicationName = "Get CDR Avaya";
body = "Detail of the message.";
imageType = 1;
messageType = 1;
requestTime = "2016-01-01 00:00:04";
sendTime = "2016-01-01 00:00:04";
subject = "Mensagem 05";
},
{
agentName = "Sant2";
applicationName = "Script Programming2";
body = "Detail of the message.";
imageType = 1;
messageType = 1;
requestTime = "2016-01-01 00:00:03";
sendTime = "2016-01-01 00:00:03";
subject = "Mensagem 04";
}
);
}
我的代码是:
let file = Bundle.main.path(forResource: "ABC", ofType: "json")! as NSString
let url = URL(fileURLWithPath: file as String)
let data = try! Data(contentsOf: url)
let json = try! JSONSerialization.jsonObject(with: data)
我的问题是:
fatal error: 'try!' expression unexpectedly raised an error: Error Domain=NSCocoaErrorDomain Code=3840 "No string key for value in object around character 6." UserInfo={NSDebugDescription=No string key for value in object around character 6.}: file /Library/Caches/com.apple.xbs/Sources/swiftlang/swiftlang-800.0.46.2/src/swift/stdlib/public/core/ErrorType.swift, line 178
我需要获取“cuaca”中的所有对象,我可以使用数组进一步使用。
最佳答案
崩溃是因为文件路径为 nil 或 url 为 nil 或数据为 nil。请添加零检查。试试下面的代码
if let file:String = Bundle.main.path(forResource: "ABC", ofType: "json")
{
if let url:URL = URL(fileURLWithPath: file)
{
if let data:NSData = NSData(contentsOf: url as URL)
{
do{
_ = try JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions())
}catch{
print(error)
}
}
}
}
关于iOS swift 3.0本地JSON解析崩溃,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39766093/