Home > Enterprise >  Do you need to create a struct with every JSON property or can you be selective? Swift
Do you need to create a struct with every JSON property or can you be selective? Swift

Time:08-10

To clarify if you are trying to decode a JSON file but are only interested in the information of some of the properties within that JSON, do you still need to create a struct to model all of the available properties or can you get away with just the ones you are interested in?

For example if I have the JSON like this.

"teamRecord": {
    "wins": 15,
    "losses": 14,
    "draws": 3,
  }

Can my struct look like this:

struct Team: Decodable {
  let wins: int
}

Or does it have to be:

struct Team: Decodable {
  let wins: int
  let losses: int
  let draws: int
}

Thanks!

CodePudding user response:

You can selectively decode only the elements of the JSON object you care about. The only requirement is that your types match the JSON objects types.

So you can safely drop the values, like you have in your example.

  • Related