我有这个JSON文件:
{
"People" : [{
{
"Name": "Jack"
"Age": 130,
"Job": "Doctor",
},
{
"Name": "Mark"
"Age": 45,
"Job": "Engineer",
},
{
"Name": "Sarah"
"Age": 27,
"Job": "Designer",
},
}]
}
以下是我使用辅助函数解析它的方法:
static func parseJson(file: String) -> [String: Any] {
let jsonFile = Bundle.main.path(forResource: file, ofType: "json")
let jsonData = NSData(contentsOfFile: jsonFile!)
let jsonDictionary = try? JSONSerialization.jsonObject(with: jsonData! as Data, options: [])
return jsonDictionary as! [String: Any] <-- Error
}
然后当我尝试初始化它时:
let data = parseJson(file: "People") as! [String: Any]
print(data["people"])
我收到此错误:
fatal error: unexpectedly found nil while unwrapping an Optional value
我在这里做错了什么?我遵循了tutorial by Apple
答案 0 :(得分:2)
始终使用某个验证程序验证您的JSON。
更正JSON格式:
{
"People" : [
{
"Name": "Jack",
"Age": 130,
"Job": "Doctor",
},
{
"Name": "Mark",
"Age": 45,
"Job": "Engineer",
},
{
"Name": "Sarah",
"Age": 27,
"Job": "Designer",
}]
}
答案 1 :(得分:1)
我看到两个问题:
第2行应为"People": [
&lt; - NO {
第18行应为]
&lt; - NO}