2

I'm consuming an API that looks like very similar to this:

{
   "email": "[email protected]",
   "settings": [
        {
            "setting_A": {
                "value": -65,
            }
        },
        {
            "setting_B": {
                "value": {
                    "b1": {
                        "val": 12,
                        "unit": "kg"
                    },
                    "b2": {
                        "val": 10,
                        "unit": "g"
                    }
                }
            }
        }
    ]
}

I'm stuck on decoding this JSON result esp. settings. Can someone help me how to?

This is what I have so far:

struct User: Decodable  {
  let email: String
  let settings: [Setting] // not sure how to do this :(
}
5
  • 1
    Are the keys inside settings always constant? Do the values corresponding to specific keys always have the same form? If not, do you know all possible keys and all possible values? Commented Feb 18, 2018 at 23:34
  • @DávidPásztor Yes, the keys and values are always consistent. No dynamically added keys or values. Commented Feb 18, 2018 at 23:42
  • 1
    @ashokgelal you can convert your json to model class here app.quicktype.io/#l=swift Commented Feb 19, 2018 at 5:05
  • 1
    @PrashantTukadiya Wow! I wish I knew this tool before. Just saved me few extra hours. Thanks a bunch! Commented Feb 19, 2018 at 18:23
  • 1
    Welcome 🤗 happy to help Commented Feb 19, 2018 at 18:32

1 Answer 1

8

After spending few hours, I ended up using https://app.quicktype.io/#l=swift as suggested by @PrashantTukadiya and got it all done in under 5 minutes. I highly recommend using that tools for your encoding/decoding needs.

Sign up to request clarification or add additional context in comments.

2 Comments

I also recommend to use this Xcode extension: github.com/quicktype/quicktype-xcode
This site uses Data(contentsOf: url) inside the model to get data from the network, which is an abomination. Otherwise, yeah, such a site could be useful, sure.

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.