iOS 11 Screencasts: What's New in Foundation - | Ray Wenderlich

In the past working with JSON meant using either NSJSONSerialization class or a third party library. Now it's a matter of implementing a simple protocol.


This is a companion discussion topic for the original entry at https://www.raywenderlich.com/4055-what-s-new-in-foundation-parsing-json-in-swift-4

Hi Brian
As always, thank you for the videos. :blush:

I have a query.
While decoding json from the NewsAPI I am trying to decode “urlsToLogo”.
I am successful if I am using
var urlsToLogos: [String : String] = [:]
But what if the values in the dictionary are of varying data types.
var urlsToLogos: [String : Any] = [:] //throws compiler error, doesn’t conform to protocol Decodable

Thanks.
Shivam

@vegetarianzombie @bdmoakley Can you please help with this one when you get a chance? Thank you - much appreciated! :]

I believe Any is not supported for this protocol.

Thanks so much! I’m glad you like the videos. Do you mind posting the code in context? I have some ideas but I’d like to see what you are doing first. Thanks!

Hi Brian
Thanks for the response.

What i did is that i parsed the ‘urlsToLogos’ array as well which we know from the json is of type [String: String].
In the Sources.swift file I added ‘let urlsToLogos: [String:String]’ in the class and ‘case urlsToLogos’ in CodingKeys enum. The parser is working fine. There is absolutely no issue with that. But if i am changing ‘urlsToLogos’ type to [String, Any], I am getting a compile time error.
Please do have a look.

When parsing JSON, there are a few types that are supported out of the box. That is, they already support the codable protocol. JSON supports a limited amount of types and will naturally map to these types.

The Any type doesn’t support JSON parsing. It’s not meant to. If you used Any, that means you’d be back to casting your JSON derived objects. This was the major pain point in working with JSON.

To learn more info about JSON, check out this article here:

https://www.raywenderlich.com/172145/encoding-decoding-and-serialization-in-swift-4

Also, we have video courses on JSON that dive deeper into the topic to give better clarity:

https://videos.raywenderlich.com/courses/96-saving-data-in-ios/lessons/12

I hope that helps!

This topic was automatically closed after 166 days. New replies are no longer allowed.