Swift - JSON嵌套结构获取具有相同键名

时间:2017-12-02 15:33:25

标签: json swift struct nested

我正在尝试解析JSONData,我目前从中得到的是datetemptext对于{{1}内的第一个块的值然而,我需要的是获取具有键名channeltemptext的所有值,包括第二个块中的值,我无法找出解决方案。

这是我的JSON:

date

这是我的结构,

{
  "query": {
    "count": 2,
    "created": "2017-12-02T15:19:36Z",
    "lang": "fr-fr",
    "results": {
      "channel": [
        {
          "item": {
            "condition": {
              "code": "26",
              "date": "Sat, 02 Dec 2017 05:00 AM AKST",
              "temp": "-1",
              "text": "Cloudy"
            }
          }
        },
        {
          "item": {
            "condition": {
              "code": "34",
              "date": "Sat, 02 Dec 2017 08:00 AM CST",
              "temp": "0",
              "text": "Mostly Sunny"
            }
          }
        }
      ]
    }
  }
}

1 个答案:

答案 0 :(得分:3)

这是一种具有多个结构且没有自定义初始化程序的不同(经典)方法

struct Root : Decodable {
    let query : Query
    var channels : [Channel] {
        return query.results.channel
    }
}

struct Query : Decodable {
    let count : Int
    let created : Date
    let lang : String
    let results : Results
}

struct Results : Decodable {
    let channel : [Channel]
}

struct Channel : Decodable {
    let item : [String : Condition]
}

struct Condition : Decodable {
    let code : String
    let date : String
    let temp : String
    let text : String
}

并打印code数组中datetemptextchannel的所有值

let jsonString = """
{
    "query": {
        "count": 2,
        "created": "2017-12-02T15:19:36Z",
        "lang": "fr-fr",
        "results": {
            "channel": [{"item": { "condition": { "code": "26", "date": "Sat, 02 Dec 2017 05:00 AM AKST", "temp": "-1", "text": "Cloudy"}}},
                        {"item": { "condition": { "code": "34", "date": "Sat, 02 Dec 2017 08:00 AM CST", "temp": "0", "text": "Mostly Sunny"}}}]
        }
    }
}
"""

let data = Data(jsonString.utf8)
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
let root = try decoder.decode(Root.self, from: data)
for channel in root.channels {
    for (_, condition) in channel.item {
        print(condition.code)
        print(condition.date)
        print(condition.temp)
        print(condition.text)
    }
}