Tuesday, 29 October 2019

Decodable for JSON with two structs under the same tag

I have this json:

{ "stuff": [
 {
 "type":"car",
 "object":{
  "a":66,
  "b":66,
  "c":66 }},
 {
 "type":"house",
 "object":{
  "d":66,
  "e":66,
  "f":66 }},
 {
 "type":"car",
 "object":{
  "a":66,
  "b":66,
  "c":66 }}
]}

As you can see for "car" and "house" there are different "object" structs, but both under the tag "object".

A simple solution is:

struct Feed: Codable {

    let stuff: [StuffItem]

    struct StuffItem: Codable {

        let type: TheType
        enum TheType: String, Codable {
            case car
            case house
        }

        let object: Object
    }

    struct Object: Codable {
        // for car type...
        var a: Int?
        var b: Int?
        var c: Int?
        // for house type...
        var d: Int?
        var e: Int?
        var d: Int?
    }
}

That works fine, and you end up with...

struct StuffItem: Codable {     
  let type: TheType
  let object: Object // it has 'both' car and house fields in there
}

It would be ideal if one ended up with something more like

struct StuffItem: Codable {     
  let type: TheType
  let car: Car
  let house: House
}

Of course you could just copy them over afterwards;

Is there some more Codable, swifty, way to handle this?

(BTW I only need to decode, never encode.)



from Decodable for JSON with two structs under the same tag

No comments:

Post a Comment