我正在嘗試決議我在我的應用程式中收到的 JSON。JSON 語法是正確的,但我無法將其決議為嵌套結構。
這是我可以在 Playground 中運行的代碼:
let message = "{\"type\":\"something\",\"data\":{\"one\":\"first\",\"two\":\"second\",\"three\":\"third\"}}"
let jsonData = message.data(using: .utf8)!
struct Message: Decodable {
let type: String
struct data: Decodable {
var one: String
var two: String
var three: String
}
}
let receivedMessage: Message = try! JSONDecoder().decode(Message.self, from: jsonData)
列印的結果是Message(type: "something"),但資料沒有被決議。
我怎樣才能正確決議資料以便以后使用它。
uj5u.com熱心網友回復:
嵌套結構/字典是鍵的值data
struct Message: Decodable {
let type: String
let data: Nested
struct Nested: Decodable {
var one: String
var two: String
var three: String
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/481014.html
