0

So I was trying JSON parsing with Decodable and the fields of the Decodable struct should match with their names in JSON but there's an object in JSON which has a "-" in its name. How do I name the field in the Struct?

JSON:

"media-metadata": [
    {
        "format": "Standard Thumbnail",
        "height": 75,
        "width": 75
    },
    {
        "format": "mediumThreeByTwo440",
        "height": 293,
        "width": 440
    }
]

Code:

struct  MediaMetadataDetails: Decodable {
    let format: String
    let height: Int
    let width: Int
}

struct MediaObject: Decodable {
    let media-metadata: [MediaMetadataDetails] // ???
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579

1 Answers1

2

You need to add CodingKeys enum

struct MediaObject: Decodable {
    let mediaMetadata: [MediaMetadataDetails] 
    enum CodingKeys: String, CodingKey {
       case mediaMetadata = "media-metadata" 
    }
}
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • 2
    Please do not abuse the gold tag badge dupe hammer so you can reopen posts to answer them. This is not the behaviour we want to encourage from new users, it sets a bad example. –  Jul 29 '19 at 07:33
  • @YvetteColomb i added the answer before making it a duplicate – Shehata Gamal Jul 29 '19 at 13:31