Prashant Tukadiya
Prashant Tukadiya

Reputation: 16456

Codable Handle dynamic key at root

I have already seen couple of similar question but I have different JSON

So I have JSON looks like below

var json = """
{
"Array1": [
{
"FinancialYear": "17-18"

}],
"Array2": [
{
"FinancialYear": "17-18"
}]
}
"""

the issue is Array1 and Array2 keys which seems to be dynamic and it is at ROOT and can be more like Array3, Array4 etc

I want to use Codable but because of dynamic key at the root (Array1,Array2) I am not able to get the rid of it.

Here is Struct that I have tried but not working

struct CodableJSON: Codable {
    var response:[String:[ArrayInside]]
    enum CodingKeys: String, CodingKey   {
        case response = "What should I write here ?" // What should be here ? 
    }

}

Upvotes: 0

Views: 306

Answers (1)

vadian
vadian

Reputation: 285240

In this case declare only the ArrayInside struct

struct ArrayInside: Decodable {
   ...
}

and decode the root object as dictionary

let result = try JSONDecoder().decode([String:[ArrayInside]].self, from: data)

Upvotes: 4

Related Questions