Home > Back-end >  Parse Json to nested Struct using Swift
Parse Json to nested Struct using Swift

Time:05-24

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.

CodePudding user response:

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
    }
}
  • Related