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.
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 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!
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: