I'm trying to implement a Decodable to parse a json request but the json request has a dictionary inside of the object.
Here is my code:
struct myStruct : Decodable {
let content: [String: Any]
}
enum CodingKeys: String, CodingKey {
case content = "content"
}
But I'm getting this error:
Type 'MyClass.myStruct' does not conform to protocol 'Decodable'
How can declare a variable as dictionary without this error?
I'll really appreciate your help
You cannot currently decode a [String: Any]
with the Swift coding framework. You'll need to drop to a lower-level deserialization strategy and decode “by hand” if you need to decode a [String: Any]
. For example, if your input is JSON, you can use Foundation's JSONSerialization
or a third-party library like SwiftyJSON.
There has been discussion of this issue on Swift Evolution: “Decode a JSON object of unknown format into a Dictionary with Decodable in Swift 4”. Apple's main Coding/Codable programmer, Itai Ferber, has been involved in the discussion and is interested in providing a solution, but it is unlikely to happen for Swift 5 (which will probably be announced at WWDC 2018 and finalized around September/October 2018).
You could copy the implementation of JSONDecoder
(it's open source) into your project and modify it to add the ability to get an unevaluated [String: Any]
. Itai discusses the required modifications in the thread I linked above.