gpt4 book ai didi

json - 使用 Swift 解析 JSON 时出现问题

转载 作者:行者123 更新时间:2023-11-30 10:01:51 25 4
gpt4 key购买 nike

我有一个包含此 person 对象的 JSON 文件。每个人都有不同的信息。这是 JSON 文件的结构。

[
{
"person": {
"name": "Dani",
"job": "Artist",
"country": "FR",
"sold": "992",
"email": "Dani",
"facebook": "Artist",
"twitter": "Dani",
"instagram": "Artist",
"snapchat": "Dani",
"photo": "Artist"
}
},
{
"person": {
"name": "Alex",
"job": "",
"country": "TU",
"sold": "992",
"email": "Dani",
"facebook": "Artist",
"twitter": "Dani",
"instagram": "Artist",
"snapchat": "Dani",
"photo": "Artist"
}
}
]

我能够打开 json 文件,但无法解析它。这是我的代码

 func lodData()
{
let data = NSData(contentsOfURL: url!)



do {
let json = try NSJSONSerialization.JSONObjectWithData(data!, options: .AllowFragments)

if let person = json["person"] as? [[String: AnyObject]] {
for p in person {
if let name = p["name"] as? String {
names.append(name)
}
}
}
} catch {
print("error serializing JSON: \(error)")
}

print(names)

}

结果名称数组仍然为空。

最佳答案

person 是 [String: String] 表示字典而不是数组..你可以这样做

 if let data = json as? [[String: AnyObject]] {
for p in data {
if let person = p["person"] as? [String: String]{
names.append(person["name"])
}
}
}

关于json - 使用 Swift 解析 JSON 时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38075754/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com