In my flutter application, I am receiving json response and can also able to parse it easily.
But At a point or a key named "data" in json response giving me dynamic value as below:
Sometime it coming like (1):
"data": {
"count": "237",
"dollars": "279370.62"
},
Sometime it coming like (2):
"data": 122093.43,
Sometime it coming like (3):
"data": {
"colas": 4,
"formulas": 0
},
and Sometime it coming like (4):
"data": "122093.43",
So How can I decide that whether is it a normal String value inside json or I need to parse a data object? and you might also noticed that the keys inside data is also getting changed.
What is the best way to handle this?
2
Answers
With the use of type dynamic we can solve this issue and then using JsonDecode functionality its easy to get values for the required json keys.
You just have to map every possible outcome for your response… one way to do it is to iterate for keys in your map, but I think that would be kind of complex because you’ll have to add extra logic once data has been retreived and not handled before that. I would so something like this:
With the code above you can handle your incoming data based on its type and work with its properties. Btw, using if statements here is fine, it makes the code more readable IMO