如何在 Swift 中解码嵌套的 JSON?

时间:2021-06-08 16:35:49

标签: ios json swift

我目前正在开展一个项目,该项目进行 API 调用并返回和解码 JSON 响应。它需要访问嵌套 json 深处的信息(响应的 URL 是 https://waterservices.usgs.gov/nwis/iv/?format=json&indent=on&sites=08155200&parameterCd=00065&siteStatus=all)。我已经想出了如何使用以下代码解码 json 的第一级/非嵌套部分:

Post(name: "ns1:timeSeriesResponseType")

然后用这个输出响应(这是我想要的):

import UIKit

struct queryInfo: Codable {
    let queryURL: String

    private enum CodingKeys: String, CodingKey {
        case queryURL = "queryURL"
    }
}

struct Values: Codable {
    let queryinfo: queryInfo

    private enum CodingKeys: String, CodingKey {
        case queryURL = "queryInfo"
    }
}

struct Post: Codable {
    let name: String
    //let scope: String
    let values: Values
    //let globalScope: Bool //true or false
}

let url = URL(string: "https://waterservices.usgs.gov/nwis/iv/?format=json&indent=on&sites=08155200&parameterCd=00065&siteStatus=all")!

URLSession.shared.dataTask(with: url) { data, _, _ in
    if let data = data {
        let posts = try! JSONDecoder().decode(Post.self, from: data)
        print(posts)
    }
}.resume()

但是,我编写的用于解码文件嵌套部分的代码:

ParseJSON.playground:11:8: error: type 'Values' does not conform to protocol 'Decodable'
struct Values: Codable {
       ^

ParseJSON.playground:15:14: note: CodingKey case 'queryURL' does not match any stored properties
        case queryURL = "queryInfo"
             ^

error: ParseJSON.playground:11:8: error: type 'Values' does not conform to protocol 'Encodable'
struct Values: Codable {
       ^

ParseJSON.playground:15:14: note: CodingKey case 'queryURL' does not match any stored properties
        case queryURL = "queryInfo"
             ^

响应错误:

class Author
  # gender
  # name
end

class Book
  # status -> ['published', 'in_progress']
  has_one :author

end

1 个答案:

答案 0 :(得分:1)

正如@Larme 已经在评论中提到的那样。 您必须更新此部分才能解决此问题。

struct Values: Codable {
    let queryinfo: queryInfo

    private enum CodingKeys: String, CodingKey {
        case queryinfo = "queryInfo"
    }
}

要获得更多信息,您可以尝试 https://app.quicktype.io/ 从任何 json 生成可解码的代码。