Anviking / Decodable

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

Decode nested json array #89

Closed icanswiftabit closed 8 years ago

icanswiftabit commented 8 years ago

Hi I love Decodable but recently I encounter this situation with nested JSON.

JSON

{
    "cars": [
        {
            "name": "bmw",
            "passagers": [
                {
                    "name": "john",
                    "age": "23"
                },
                {
                    "name": "lucy",
                    "age": "23"
                }
            ]
        },
        {
            "name": "ford",
            "passagers": [
                {
                    "name": "błażej",
                    "age": "27"
                },
                {
                    "name": "marcy",
                    "age": "27"
                }
            ]
        }
    ]
}

Structs

struct Car:Decodable{
    var name:String
    var passagers:[Passager]
    static func decode(json:AnyObject) throws -> Passager {
        return try DirectionJson(
            name: json => "name",
            passagers: json => [Passager].decode //? error, so how?
        )
    }
}

struct Passager:Decodable{
    var name:String
    var age:Int
    static func decode(json:AnyObject) throws -> Passager {
        return try DirectionJson(
            name: json => "name",
            age: json => "age"
        )
    }
}

I was hoping that whole json would be decoded by single [Car].decode(json). But I'm not sure how I should handle [Passager] in Car.

Anviking commented 8 years ago

It should be enough to write passagers: json => "passagers", and the type inference should figure it out.

icanswiftabit commented 8 years ago

That thank that works great. Again thank for you work.