[swift-users] Decode a JSON object of unknown format into a Dictionary with Decodable in Swift 4
Kevin Wooten
kdubb at me.com
Thu Jun 29 14:21:03 CDT 2017
> Hi Jon,
>
> I just joined this mailing list and have tried to catch up on the
> history of this thread, so please excuse me if I’ve missed something.
>
> I’m sorry the Codable API at the moment does not answer your needs —
> you’re clearly not the only one who’s run into this, so let’s see
> how we can work together to make the API better for everyone.
> For one thing, in the case of grabbing a subtree of JSON as
> "unevaluated" or "unmapped" (as it appears to be in the metadata case),
> it should be fairly simple to add a `JSONDecoder.UnevaluatedJSON` type
> that will allow you to essentially decode that part of the tree as an
> `Any`. `JSONDecoder` would have knowledge of this type and would be able
> to return the subtree inside of it — you’d decode a property as
> `JSONDecoder.UnevaluatedJSON.self` and access the contents through `var
> value: Any?`, or something similar. This would be simple additive API,
> which although might not make it in the upcoming betas, should be fairly
> simple introduce. Would this solve that use case?
>
> We’re also working on improving `NSISO8601DateFormatter`. I don’t
> think I saw it in any of your emails — what specific use case are you
> looking for that it doesn’t at the moment support?
>
> — Itai
Itai,
Is this a formal solution that is going to be implemented? This would solve just about every issue I currently have with Decodable.
Two points…
1) Putting it on `JSONDecoder` seems dubious since you’d only have access to `Decoder` (although conditional casting could solve that). It seems adding the method to `Decoder` and using `Decoder.Unevaluated.self` as the requested type, would be more useful. A user could then conditionally cast that value to things like `[String: Any]` and possibly use its contents generically.
2) Matching it with an equivalent on `Encoder` would be great as well. We take in JSON that has “metaData” like one aforementioned exampled. We then have to send back the equivalent metadata during a subsequent update; without ever inspecting or altering the unevaluated data. Being able encode a `Decoder.Unevaluated` would solve that problem as well.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170629/d75780bf/attachment.html>
More information about the swift-users
mailing list