bignerdranch / Freddy

A reusable framework for parsing JSON in Swift.
MIT License
1.09k stars 120 forks source link

Fixing missingKeyBecomesNil being recursive #256

Open nerdsupremacist opened 7 years ago

nerdsupremacist commented 7 years ago

Here's a fix for the .missingKeyBecomesNil Option catching errors from decode calls below.

For instance:

     struct A: JSONDecodable {
            let b: B?

            init(json: JSON) throws {
                b = try json.decode(at: "b", alongPath: [.missingKeyBecomesNil])
            }

        }

        struct B: JSONDecodable {
            let string: String

            init(json: JSON) throws {
                string = try json.decode(at: "string")
            }
        }

If I were to call decode with the following invalid json:

{
    "b": {

    }
}

The previous implementation wouldn't throw an error but return A(b: nil)

If you still want the previous functionality you can use the parameter applyRecursively.

 b = try json.decode(at: "b", alongPath: [.missingKeyBecomesNil]) // Will throw an error
 b = try json.decode(at: "b", alongPath: [.missingKeyBecomesNil], applyRecursively: true) // nil
nerdsupremacist commented 7 years ago

@zwaldowski I hope you like this! ;)

nerdsupremacist commented 7 years ago

@mdmathias thoughts? I could also make the applyRecursively flag a case in JSON.SubscriptingOptions if you prefer. Although it could lead to some confusion