Anviking / Decodable

[Probably deprecated] Swift 2/3 JSON unmarshalling done (more) right
MIT License
1.04k stars 73 forks source link

Handling situation when json is just an array #147

Open icanswiftabit opened 7 years ago

icanswiftabit commented 7 years ago

So many times I did have situations with JSONs

For example json with Events

[{
    "end_date": "2017-04-23T16:52:27.799Z",
    "name": "Session 0.2.1",
    "start_date": "2017-04-23T15:52:27.799Z"
},{
    "end_date": "2017-04-23T16:52:27.799Z",
    "name": "Session 0.2.2",
    "start_date": "2017-04-23T15:52:27.799Z"
},
{
    "end_date": "2017-04-23T16:52:27.799Z",
    "name": "Session 0.2.3",
    "start_date": "2017-04-23T15:52:27.799Z"
}]

So decoded struct should look like

struct JsonReposne: Decodable {
let events: [Event]

    static func decode(_ json: Any) throws -> JsonReposne {
        return try JsonReposne(
            events: json // but this will not work 
        )
    }
}

Workaround is to put JSON into dictionary and pass that dictionary

    static func decode(_ json: Any) throws -> JsonReposne {
        let data = ["data": json] as Any
        return try JsonReposne(
            events: data => "data" 
        )
    }

Maybe this is worth adding to Decodable itself?

Anviking commented 7 years ago

You can use [Event].decode(json), or alternatively (I think) json => []