skip to Main Content

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


  1. 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:

    struct Item: Codable {
        let itemInfo: ItemInfo
        let movieData: MovieData
    }
    
    // MARK: - ItemInfo
    struct ItemInfo: Codable {
        let name: String
        let movieImage: String                    // possibly `URL` would be more appropriate
        let youtubeTrailer, description: String
        let backdropPath: [String]                // possibly `[URL]` would be more appropriate
        let video, audio: Media
    }
    
    // MARK: - Media
    struct Media: Codable {
        let index: Int
        let codecName, codecLongName, profile: String
    }
    
    // MARK: - MovieData
    struct MovieData: Codable, Identifiable {
        let id: Int
        let name, added, secondaryId: String
    }
    

    and then you can decode it:

    do {
        let decoder = JSONDecoder()
        decoder.keyDecodingStrategy = .convertFromSnakeCase
        let object = try decoder.decode(Item.self, from: data)
        print(object)
    } catch {
        print(error)
    }
    

    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 a keyDecodingStrategy for your JSONDecoder of convertFromSnakeCase, reducing the amount of noise in the code.


    As an aside, looking at the JSON, it looks like movie_image and backdropPath might be URL 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search