简体   繁体   English

使用 Swift 将 Json 解析为嵌套结构

[英]Parse Json to nested Struct using Swift

I am trying to parse a JSON that I am receiving in my Application.我正在尝试解析我在我的应用程序中收到的 JSON。 The JSON Syntax is correct but I am unable to parse it into a nested Struct. JSON 语法是正确的,但我无法将其解析为嵌套结构。

Here is my code that can be run in Playground:这是我可以在 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)

The printed Result is Message(type: "something") but the data is not parsed.打印的 Result 是Message(type: "something")但未解析数据。

How can I parse the data correctly to use it afterwards.我怎样才能正确解析数据以便以后使用它。

The nested struct/dictionary is the value for key data嵌套结构/字典是关键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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM