簡體   English   中英

在Swift4上解析JSON

[英]Parsing JSON on Swift4

我正在嘗試解析一個簡單的JSON,但我不明白自己在做錯什么,這不是我嘗試過的唯一代碼。 我只是Swift代碼的初學者,嘗試學習。 這是我得到的:

MyThing(feeds: [TempCode.MyThing.Feeds(field1: "19.06")])

這是我的代碼。

import Foundation

let data = """
    {
    "channel": {
        "id": 21548,
        "name": "House",
        "field1": "Temperature",
        "field2": "Humidity",
        "updated_at": "2018-02-17T11:10:13Z",
        "last_entry_id": 14878
    },
    "feeds": [
        {
            "created_at": "2018-02-17T11:10:13Z",
            "entry_id": 14878,
            "field1": "19.06",
            "field2": "58.60"
        }
    ]
}
""".data(using: .utf8)!

struct MyThing: Codable {
   let feeds: [Feeds]
   struct Feeds: Codable {
      let field1: String
}
enum CodingKeys : String, CodingKey {
    case feeds
}
}


let decoder = JSONDecoder()
let thingData = try decoder.decode(MyThing.self, from: data)
print(thingData)

我要實現的是僅打印field1和field2的值。 謝謝。

  • 首先,您必須添加一個屬性以對field2進行解碼
  • 第二,CodingKeys是冗余的,您可以忽略它們。
  • 第三,建議以單數形式命名結構。

struct MyThing: Codable {
    let feeds: [Feed]
    struct Feed: Codable {
        let field1: String
        let field2: String
    }
}

要僅打印field1field2使用循環遍歷feeds數組

for feed in thingData.feeds {
    print(feed.field1, feed.field2)
}

暫無
暫無

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

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