As always, thank you for the videos.
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
@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!
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:
Also, we have video courses on JSON that dive deeper into the topic to give better clarity:
I hope that helps!
This topic was automatically closed after 166 days. New replies are no longer allowed.