[swift-users] Decode a JSON object of unknown format into a Dictionary with Decodable in Swift 4
Jon Shier
jon at jonshier.com
Sun Jun 18 02:21:10 CDT 2017
Your issue here is Any, which will likely never be Decodable. You’ll need an actual type to contain the raw JSON. Hilariously, I have to wonder if Argo’s JSON enum could be made Decodable, as it can represent every valid JSON type typically contained in the Any returned by JSONSerialization. Yet another reason why Swift needs a real JSON serialization.
Jon Shier
> On Jun 17, 2017, at 10:07 PM, Chris Anderson via swift-users <swift-users at swift.org> wrote:
>
> Say I have a JSON object such as:
>
> {
> "id": "4yq6txdpfadhbaqnwp3",
> "email": "john.doe at example.com <mailto:john.doe at example.com>",
> "name":"John Doe",
> "metadata": {
> "link_id": "linked-id",
> "buy_count": 4
> }
> }
>
> And with a struct of:
>
> struct User: Codable {
> var id: String
> var email: String
> var name: String
> }
>
> How can I decode the `metadata` field into a Dictionary?
>
> I’ve tried doing things such as, in my struct,
>
> var metadata: Dictionary
>
> or
>
> var metadata: [String: Any]
>
> But I get the error
>
> MyPlayground.playground:3:7: note: cannot automatically synthesize 'Encodable' because '<<error type>>' does not conform to 'Encodable'
> var metadata: Dictionary
>
> A meta or metadata field on many APIs (such as www.stripe.com <http://www.stripe.com/>) can contain whatever you want, and I still want to be able to process it on the Swift end. How can I store that meta data field into a Dictionary that I can parse apart manually after?
>
> Thanks!
>
> Chris Anderson
>
>
>
>
>
> _______________________________________________
> swift-users mailing list
> swift-users at swift.org
> https://lists.swift.org/mailman/listinfo/swift-users
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-users/attachments/20170618/9f08edcf/attachment.html>
More information about the swift-users
mailing list