Got a little lost while trying to decode a JSON object with multiple objects within it in from an API call, hopefully I can get some guidance/examples of how to solve it.
This is the JSON object:
{
"item_info": {
"name": "Example Name",
"movie_image": "https://google.com",
"youtube_trailer": "123",
"description": "lorem ispum",
"backdrop_path": [
"https://google.com"
],
"video": {
"index": 0,
"codec_name": "h264",
"codec_long_name": "H.264 / AVC / MPEG-4 AVC / MPEG-4 part 10",
"profile": "High",
},
"audio": {
"index": 1,
"codec_name": "aac",
"codec_long_name": "AAC (Advanced Audio Coding)",
"profile": "LC",
}
},
"movie_data": {
"id": 1,
"name": "Example Name",
"added": "1663373489",
"secondary_id": "298",
}
}
Thank you for your help!
2
Answers
Quicktype io
for converting json into codable model
reference article on how to parse json
The QuickType.io site, as suggested by Bhagwan Ranpura (+1), can jumpstart this for you. Once you clean up the code a bit, you might end up with something like:
and then you can decode it:
Note, the Quicktype.io site will suggest explicit
CodingKeys
to map between the snakecase keys in the JSON and the swifty camelcase naming convention, but this can be achieved more economically by specifying akeyDecodingStrategy
for yourJSONDecoder
ofconvertFromSnakeCase
, reducing the amount of noise in the code.As an aside, looking at the JSON, it looks like
movie_image
andbackdropPath
might beURL
and[URL]
types, respectively, but you would want to look at the documentation for the source of this JSON to confirm whether they will always be URLs or not. Likewise, when looking at a short JSON, we cannot be sure whether some of these properties should be optional, so again, you would want to refer to the documentation.But hopefully this gets you started.