UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Codable for parsing json with dynamic keys

Forums > Swift

Hi folks,

I'm 1 month into the world of Swift/SwiftUI coding and am building an app for fun that fetches stock data. Right now I'm trying to get the nested API results to conform to a codable model. I'm having trouble working with json where the first key is dynamic.

For example:

{
  "AAPL":{"quote":{},"chart":[]}, 
  "FB":{"quote":{},"chart":[]},
  "MSFT":{"quote":{},"chart":[]}
}

How would I structure my model to allow for the first key to be dynamic? Thanks for any help or pointers! I've been reading a lot of guides but they all seem to cover the basic cases where the keys are predictable and the most you need to do is convert to camelcase.

3      

In cases such as this the way to go is mostly to implement the decoder yourself. https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types at the bottom is a small example

3      

I got the dynamic key part working but now I need to figure out how to add a nested container to support the many quote {} properties:

https://gist.github.com/stammy/0872636a4c740e8a2011e57eaf09bbff

Still trying to learn the ins and outs of encode/decode.

3      

BUILD THE ULTIMATE PORTFOLIO APP Most Swift tutorials help you solve one specific problem, but in my Ultimate Portfolio App series I show you how to get all the best practices into a single app: architecture, testing, performance, accessibility, localization, project organization, and so much more, all while building a SwiftUI app that works on iOS, macOS and watchOS.

Get it on Hacking with Swift+

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.