【发布时间】:2020-09-08 23:56:33
【问题描述】:
在我进行 api 调用后,我有一个以下 json
[{"breeds":
[{"weight":{"imperial":"7 - 14","metric":"3 - 6"},"id":"ebur","description":" Something ","child_friendly":4,}]
,"url":"https://cdn2.thecatapi.com/images/YOjBThApG.jpg","width":2838,"height":4518}]
如您所见,有嵌套数组和此 api 调用的输出
我想得到Id 和url。我就这样处理我的 dataTask 输出
let jsonResponse = try? JSONSerialization.jsonObject(with: data!, options: [])
guard let jsonArray = jsonResponse as? [[String: Any]] else {
return
}
所以我可以毫无问题地访问网址print(jsonArray[0]["url"]),我也可以访问jsonArray[0]["breeds"]。但是,我不能做jsonArray[0]["breeds"]["decription"] 或jsonArray[0]["breeds"]["id"]。因为我收到以下错误Value of type 'Any?' has no subscripts 我怀疑问题出在[[String: Any]]。我如何将我的 jsonResponse 转换更改为数组以获得调用的正确输出
【问题讨论】:
-
你为什么不使用
Codable? -
如何使用 Codable
标签: arrays json swift nsarray swift5