簡體   English   中英

如何解碼 Swift 中的嵌套 JSON?

[英]How to decode a nested JSON in Swift?

我目前正在開展一個項目,該項目進行 API 調用並返回和解碼 JSON 響應。 It needs to access information deep within a nested json (the URL for the response is https://waterservices.usgs.gov/nwis/iv/?format=json&indent=on&sites=08155200&parameterCd=00065&siteStatus=all ). 我已經弄清楚如何使用以下代碼解碼 json 的第一級/非嵌套部分:

import UIKit

struct Post: Codable {
    let name: String
}

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()

然后用這個 output 響應(這就是我想要的):

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"
             ^

正如@Larme 已經在評論中提到的那樣。 您必須更新此部分才能解決此問題。

struct Values: Codable {
    let queryinfo: queryInfo

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

要獲得更多信息,您可以嘗試https://app.quicktype.io/從任何 json 生成可解碼代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM