[swift-users] Decode a JSON object of unknown format into a Dictionary with Decodable in Swift 4
Rien
Rien at Balancingrock.nl
Sun Jun 18 02:21:26 CDT 2017
Dang, hit send too soon. Sorry.
This does not address your question, so please ignore… (foot in mouth)!
Regards,
Rien
Site: http://balancingrock.nl
Blog: http://swiftrien.blogspot.com
Github: http://github.com/Balancingrock
Project: http://swiftfire.nl - An HTTP(S) web server framework in Swift
> On 18 Jun 2017, at 09:19, Rien <Rien at Balancingrock.nl> wrote:
>
> Are you looking for a general purpose JSON interpreter / API ?
>
> There are many of them around, and in fact I do have my own: https://github.com/Balancingrock/VJson
>
> With VJson I would write:
>
> let json = VJson.parse(… your json object…)
>
> and then access the metadata as:
>
> let buyCount = (json | ”metadata” | ”buy_count”)?.intValue
>
> or:
>
> var buyCount: Int &= json | “metadata” | “buy_count”
>
> To loop over the content of metadata:
>
> for item in (json | “metadata”) ?? [ ] {
> print (item.nameValue)
> switch item.type {
> case .object: …
> case .number: …
> case .string: …
> etc...
> }
> }
>
> Obviously I am plugging my own code here, but there are many others around, I understand that SwiftyJSON is quite popular but I have not used that myself.
>
> Regards,
> Rien
>
> Site: http://balancingrock.nl
> Blog: http://swiftrien.blogspot.com
> Github: http://github.com/Balancingrock
> Project: http://swiftfire.nl - An HTTP(S) web server framework in Swift
>
>
>
>
>
>
>
>> On 18 Jun 2017, at 04:07, 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",
>> "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) 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
>
More information about the swift-users
mailing list