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
Well... technically you could do this but it will require you to use a third party component SwiftyJSON for the dictionary representation.
Also, I am assuming you're doing this because content
might have non-normalized data and that you intentionally want to treat it as a dictionary.
In that case, go ahead with this:
import SwiftyJSON
struct MyStruct : Decodable {
//... your other Decodable objects like
var name: String
//the [String:Any] object
var content: JSON
}
Here, JSON
is the SwiftyJSON object that will stand in for your dictionary. Infact it would stand in for an array too.
let jsonData = """
{
"name": "Swifty",
"content": {
"id": 1,
"color": "blue",
"status": true,
"details": {
"array" : [1,2,3],
"color" : "red"
}
}
}
""".data(using: .utf8)!
do {
let test = try JSONDecoder().decode(MyStruct.self,
from: jsonData)
print(test)
}
catch {
print(error)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With