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: