TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

Decode JSON when dictionary keys are unknown

Forums > Swift

Part of some tasks we have is a required key in json which might have key:values or it might not, it might also have nested dictionaries or arrays. Essentially, under "required_payload_params":{} is completely unknown. Is there a way to decode this information? When I try [String: Any] I get the error "Type 'Any' cannot conform to 'Decodable'". Every task is specific to a single job so there is no way we would be able to make the required section all structured the same. Currently it could be managable to do by hand but will become unfeasable as we utilize this more and create more tasks.

This is a few example of how the dictionary could look like

"required_payload_params":{}
"required_payload_params": {
      "app_type": {
        "description": "Just some filler",
        "allowed_values": [
          "Filler 1",
          "Filler 2",
          "Filler 3"
        ]
      },
      "app_id": {
        "description": "Filler ID"
      }
    }
"required_payload_params": {
      "device_type": {
        "description": "Filler description",
        "allowed_values": [
          "Filler 1",
          "Filler 2"
        ]
      },
      "device_id": {
        "description": "Filler ID"
      }
    }
"required_payload_params": {
      "hostname": {
        "description": "Filler 1"
      },
      "port": {
        "description": "Filler 2"
      }
    }

3      

I think your best bet here is not to use Codable but rather to use the older JSONSerialization method of decoding JSON.

If you google "Decoding Unknown Data with Codable" you can find a blog post about doing something similar to what you are asking but using a package from Flight School to add an AnyDecodable type to your project. (Sorry for not linking directly but apparently we have new anti-spam measures here that are blocking the URL I'm trying to post.)

The Flight School Guide to Codable (again, google it) has a section in chapter 3 regarding decoding multiple representations that has more info on how to use AnyDecodable. And the book is free now so I would highly recommend it.

3      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.