0

In my current project when using Decodable we have the problem of models that look like this:

{
    "beers": [ {...} ]
}

the solution to solve this is to have something like this:

struct BeerList : Codable {
   let beers: [Beer]
}

My question is there way to parse this avoid this BeerList Struct ? And simply return an array of [Beer].

BTW the example I'm giving here is not the real one you can also find it here https://benscheirman.com/2017/06/swift-json/

PedroAGSantos
  • 2,336
  • 2
  • 17
  • 34
  • https://stackoverflow.com/a/44723563/1801544 ? – Larme Jul 05 '18 at 15:23
  • it's similar but the root node is matching the type inside the array. ex. beers != Beer – PedroAGSantos Jul 05 '18 at 15:28
  • In your link, there is the part "Customizing Key Names" where you can for instance use your own "variable names", but tell the the decoder that it correspond to a different key name. I guess it could work. – Larme Jul 05 '18 at 15:31
  • But how would you avoid the struct? Because the Keys can be customised inside the struct. – PedroAGSantos Jul 05 '18 at 15:35
  • You can customize (almost) everything, but the more custom the more code to write, in this case you have to specify CodingKeys and write an initializer. You get the magic of `Codable` (no extra code) only if the structs match exactly the JSON – vadian Jul 05 '18 at 19:05

0 Answers0