[英]Parse Json to nested Struct using Swift
我正在尝试解析我在我的应用程序中收到的 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)
打印的 Result 是Message(type: "something")
但未解析数据。
我怎样才能正确解析数据以便以后使用它。
嵌套结构/字典是关键data
的值
struct Message: Decodable {
let type: String
let data: Nested
struct Nested: Decodable {
var one: String
var two: String
var three: String
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.