Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dictionary of String:Any does not conform to protocol 'Decodable' [duplicate]

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

like image 665
user2924482 Avatar asked Dec 17 '22 23:12

user2924482


1 Answers

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.


Working Example:

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)
}
like image 86
staticVoidMan Avatar answered May 16 '23 06:05

staticVoidMan