使用 Swift 5 读取 Json 个数组
Reading Json arrays with Swift 5
我有一个关注者 json,而在我拨打 api 电话后
[{"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
}
所以我可以毫无问题地访问 url 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 转换更改为数组以获得正确的调用输出
您必须转换任何下标值
if let breeds = jsonArray.first?["breeds"] as? [[String:Any]],
let description = breeds.first?["description"] as? String {
print(description)
}
您应该使用 Codable and can use Quicktype 从 json 轻松生成您的结构。
import Foundation
// MARK: - Parameters
struct Parameters: Codable {
let breeds: [Breed]?
let url: String?
let width, height: Int?
}
// MARK: - Breed
struct Breed: Codable {
let weight: Weight?
let id, breedDescription: String?
let childFriendly: Int?
enum CodingKeys: String, CodingKey {
case weight, id
case breedDescription = "description"
case childFriendly = "child_friendly"
}
}
// MARK: - Weight
struct Weight: Codable {
let imperial, metric: String?
}
我有一个关注者 json,而在我拨打 api 电话后
[{"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
}
所以我可以毫无问题地访问 url 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 转换更改为数组以获得正确的调用输出
您必须转换任何下标值
if let breeds = jsonArray.first?["breeds"] as? [[String:Any]],
let description = breeds.first?["description"] as? String {
print(description)
}
您应该使用 Codable and can use Quicktype 从 json 轻松生成您的结构。
import Foundation
// MARK: - Parameters
struct Parameters: Codable {
let breeds: [Breed]?
let url: String?
let width, height: Int?
}
// MARK: - Breed
struct Breed: Codable {
let weight: Weight?
let id, breedDescription: String?
let childFriendly: Int?
enum CodingKeys: String, CodingKey {
case weight, id
case breedDescription = "description"
case childFriendly = "child_friendly"
}
}
// MARK: - Weight
struct Weight: Codable {
let imperial, metric: String?
}