【问题标题】:Reading Json arrays with Swift 5使用 Swift 5 读取 Json 数组
【发布时间】: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 调用的输出 我想得到Idurl。我就这样处理我的 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


【解决方案1】:

你必须转换任何下标值

if let breeds = jsonArray.first?["breeds"] as? [[String:Any]],
   let description = breeds.first?["description"] as? String {
     print(description)
}

【讨论】:

    【解决方案2】:

    您应该使用Codable 并且可以使用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?
    }
    

    【讨论】:

    • 谢谢!但是当我执行do { let breed = try JSONDecoder().decode([Breed].self, from: data!) } catch { print(error) } 时,我收到一个错误keyNotFound 我是否必须在输入 Json 数据之前对其进行预处理?
    • 不,你只需要像 json 一样组成你的结构。
    • 你的data 不是[Breed] 它就像我的帖子中的Parameters
    猜你喜欢
    • 1970-01-01
    • 2021-04-01
    • 1970-01-01
    • 2021-04-03
    • 1970-01-01
    • 1970-01-01
    • 2021-06-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多