简体   繁体   中英

Parse Json to nested Struct using Swift

I am trying to parse a JSON that I am receiving in my Application. The JSON Syntax is correct but I am unable to parse it into a nested Struct.

Here is my code that can be run in 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.

How can I parse the data correctly to use it afterwards.

The nested struct/dictionary is the value for key data

struct Message: Decodable {
    let type: String
    let data: Nested
    
    struct Nested: Decodable {
        var one: String
        var two: String
        var three: String
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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