0

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 ? 
    }

}
4
  • I think its not possible. You have to change structure Commented Dec 27, 2018 at 9:58
  • Did you check answers on this post: stackoverflow.com/questions/50713638/… Commented Dec 27, 2018 at 10:04
  • 1
    @emrepun Yes I have seen this But If you observe periods is root key so there is no issue with that but I have dynamic root key Commented Dec 27, 2018 at 10:12
  • @Tobi Thanks comment , Can't be sure. about that. I don't want to bother in future for changes in key. so I am searching for generic solution that can work in all cases as accepted answer provided me. Commented Dec 27, 2018 at 10:24

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Yes , That should work !! I have fixed it with long route , Thanks vadian you always suggests best

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.