用swift 3解析json不适合我
几天来,我一直试图从下面的json文件中获取“名称”,但没有成功。谁能给我指一下正确的方向吗?我已成功访问结果数组,但没有访问“name”变量用swift 3解析json不适合我,json,swift3,Json,Swift3,几天来,我一直试图从下面的json文件中获取“名称”,但没有成功。谁能给我指一下正确的方向吗?我已成功访问结果数组,但没有访问“name”变量 { "count": 7, "next": null, "previous": null, "results": [ { "id": 10, "name": "Abs" }, { "id": 8, "name": "Arms" }, { "id
{
"count": 7,
"next": null,
"previous": null,
"results": [
{
"id": 10,
"name": "Abs"
},
{
"id": 8,
"name": "Arms"
},
{
"id": 12,
"name": "Back"
},
{
"id": 14,
"name": "Calves"
},
{
"id": 11,
"name": "Chest"
},
{
"id": 9,
"name": "Legs"
},
{
"id": 13,
"name": "Shoulders"
}
]
}
我的代码是这样的
let url = URL(string: "https://wger.de/api/v2/exercisecategory")!
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
if error != nil {
print(error!)
} else {
if let content = data {
do {
let json = try? JSONSerialization.jsonObject(with: content, options:[]) {
if let content = json as? [String: Any] {
if let results = content["results"] as? [Any] {
for result in results {
if let bodypart = result["name"] as! [String: Any] {
print(bodypart)
}
}
}
}
}
}
}
}
}
问题是您正在将
name
强制转换为Dictionary
,但这只是String
而已,您还需要将结果强制转换为Dictionary的数组,而不是Any的数组。所以整个代码都是这样的
if let json = try? JSONSerialization.jsonObject(with: content, options:[]),
let content = json as? [String: Any],
let results = content["results"] as? [[String:Any]] {
for result in results {
if let bodypart = result["name"] as? String {
print(bodypart)
}
}
}
@Niklas欢迎伙伴:)