Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Swift JSONDecoder: how to decode a JSON with unknown keys at the top-level?

I would like to know how I can decode this JSON:

{
    "unknown_key1": {
        "info": "Info text",
        "text": "More text"
    },
    "unknown_key2": {
        "info": "Info text",
        "text": "More text"
    },
    ...
}

I have started writing something like this:

JSONDecode().decode(Test.self, from: data)

Test

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

struct Test: Decodable {
    let content: [String: Content]
}

struct Content: Decodable {
    let info: String
    let text: String
}

But this doesn’t work and I have no idea of what to do

(I want to emphasize on the fact that I have set unknown_key1 and unknown_key2 as examples but these keys can be absolutely anything else)

Thank you for your help

>Solution :

The JSON structure you posted is a Dictionary [String:Content].

Decoding would look like:

try JSONDecoder().decode([String:Content].self, from: data)

there is no top level element.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading