I need your help on decoding this piece of JSON
{
"json": {
"firstItem": {
"key": "key",
"value": "data"
},
"secondItem": {
"key": "key",
"value": "data"
},
"thirdItem": {
"key": "key",
"value": "data"
},.......... //All of the data, which is a lot, comes like this
}
}
I want to be able to decode this data, but can’t figure out a way without having to write too much code because there are a lot of items. Is it possible to be able to decode this JSON maybe into a nesting of dictionaries, or even better into an array of item objects with just key and value attributes? Thanks in advance
4
Answers
With Swifts structs combined with Codable we can achieve very clean and nice solution to the problem.
Declare Item struct
helper struct will be useful when retrieving values from each item contained within the json dictionary
Decode the JSON
now, considering the json is a string value, you can decode it easily with JSONDecoder
I went old school with my answer:
Create a custom type for your key/value pairs
and then decode them into an array like this
If you don’t know the keys of the nesting json you can simply decode it as a dictionary of items:
This will print: