1

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.

1 Answer 1

3

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
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.