[英]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
進行解碼 struct MyThing: Codable {
let feeds: [Feed]
struct Feed: Codable {
let field1: String
let field2: String
}
}
要僅打印field1
和field2
使用循環遍歷feeds
數組
for feed in thingData.feeds {
print(feed.field1, feed.field2)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.