Parsing JSON in Flutter!
Working with APIs? The response usually comes in JSON format!
So, whenever you work with API, we usually get responses in JSON format. JSON format looks somewhat like the below:
{
"name": "Abhishek",
"age": 22,
"technology": [
{
"name": "Flutter",
"experience": 2
},
{
"name": "GIT",
"experience": 2
}
]
}
Now one way to parse JSON is to manually parse. However, when you are working with long responses, it becomes difficult.
It’s better to use model classes for the same. So we have a website where we just need to provide our entire JSON. You can check it out at: https://app.quicktype.io and select language as Dart
For the above JSON, we will get the following model class:
So you can see it becomes so simple to use quicktype to generate model classes. However, we should always add one more thing i.e. json.containsKey and whether the data is null or not. So after adding that, we will have the following model class:
This will make your app work even if the response missed some key or if any value is null.
So, it’s preferable to use QuickType as it makes your development faster.
Note: You can of course use Null Safety for checking null conditions. Eg:
name: json.containsKey("name") ? json["name"] ?? "" : "",
Now, if you wish to parse your API Response, simply call our function as:
Welcome _data = welcomeFromJson(response.body);
To access data:
print(_data.name);
Hope you enjoyed this article!
If you loved it, you can Buy Me A Coffee!
Don’t stop, until you are breathing!💙
- Abhishek Doshi