Uncategorized

JSON Parsing in Dart/Flutter

By 8 January 2021 No Comments

JSON Parsing in Dart/Flutter

JSON Parsing in Dart/Flutter

Sharing is caring!

When I started working with API in Flutter, I found it difficult to play with JSON. And I’m sure it confuses a lot of you beginners. So here I am providing you all the basics that you should know for JSON parsing in Flutter. We’ll look at the ways to convert/parse JSON string into Object, Nested Object, parse JSON array, an array of JSON objects into List.

Dart has built-in support for parsing json. With the help of dart:convert library we can convert the given JSON string to a Map with string keys and dynamic objects. You can parse JSON directly and use the map or you can parse it and put it into a typed object so that your data has more structure and it’s easier to maintain.

Read- How to render forms from JSON in flutter?

Let’s start with a simple JSON string, and then we will go to the complex JSON. Before we start parsing we need to find out the structure of JSON. A JSON string can have either a Map(Key-value pair) or List of objects. So remember two things:

  1. JSON string starts with curly braces {} is a Map object.
  2. JSON string starts with square brackets [] is List of maps.

1. Parse JSON String Having Map Object

{
“id”:1,
“movie_name”:”3 Idiots”
}

Direct parsing :

var jsonData = ‘{ “id” : 1, “movie_name” : “3 Idiots”}’;
var parsedJson = json.decode(jsonData);
print(parsedJson);

This will print the result like:

{id: 1, movie_name: 3 Idiots}

Now we can get value from parsedJson:

var id = parsedJson[‘id’];
var movieName = parsedJson[‘movie_name’];

Parse into an object:

Create a PODO(Plain Old Dart Object) with a constructor having named and optional parameters and then create factory method to parse Map in to object

Movie({this.id, this.movieName});
factory Movie.fromJson(Map<String, dynamic> parsedJson){
return Movie(
id: parsedJson[‘id’],
movieName: parsedJson[‘movie_name’
);
}

Now we can use this method to parse json to Movie object. Here how we can do this:

String jsonString = ‘{ “id” : 1, “movie_name” : “3 Idiots”}’;
final jsonResponse = json.decode(jsonString); //it will decode string to map
Movie movie = new Movie.fromJson(jsonResponse);
print(‘Name: ${movie.movieName}’);

2. Parse JSON String Having Nested Object

Now what if we have another object within this movie object then how can we parse this. Lets see:

{
“id”: 1,
“movie _name”:”3 Idiots”,
“director” : {
“first_name” : “Rajkumar”,
“last_name” : “Hirani”,
“age” : 57

}

So for parsing this we again make PODO for director object and then use it in movies class. I have created both classes in the same file.

class Movie{
  int id;
String movieName;
Director director;

Movie({this.id, this.movieName, this.director});
factory Movie.fromJson(Map<String, dynamic> parsedJson){
return Movie(
id: parsedJson[‘id’],
movieName: parsedJson[‘movie_name’],
director: Director.fromJson(parsedJson[‘director’])
);
}
}

class Director{
  String firstName;
String lastName;
int age;
Director({this.firstName, this.lastName, this.age});
factory Director.fromJson(Map<String, dynamic> parsedJson){
return Director(
firstName: parsedJson[‘first_name’],
  lastName: parsedJson[‘last_name’],
age: parsedJson[‘age’]
);
  }
}

Here we use the director class from the Json method inside the Movie class to parse the director object. We can parse the movie json using jsonDecode as we used earlier:

String movieJson = ‘{“id”: 1,”movie _name”:”3 Idiots”,”director”{“first_name” : “Rajkumar”,”last_name” : “Hirani”,”age” : 57}}’;
Movie movie = Movie.fromJson(json.decode(movieJson));
Director director = movie.director;
print(director.firstName);

3. Parse JSON String Having List of Objects

{
“id”: 1,
“movie _name”:”3 Idiots”,
“director” : {
“first_name” : “Rajkumar”,
“last_name” : “Hirani”,
“age” : 57
},
“actors” : [
{
“name” : “Aamir khan”,
“cast_name” : “Rancho”
},
{
“name” : “Kareena kapoor”,
“cast_name” : “Piya”
},
]
}

To parse this we again create PODO for actor like this:

class Actor{
String name;
  String castName;
  Actor({this.name, this.castName});
  factory Actor.fromJson(Map<String, dynamic> parsedJson){
    return Actor(
       name: parsedJson[‘name’],
       castName: parsedJson[‘cast_name’],
    );
  }
}

Now we parse it in the list.
– First we retrieve the JSON data.
– Get the JSON array.
– Iterate the JSON array and map to the objects.

var actorArray = parsedJson[‘actors’] as List; 
List<Actor> actors = actorArray.map((e) => Actor.fromJson(e)).toList();

Here is the complete code of Movie class

class Movie{
int id;
   String movieName;
Director director;
List<Actor> actorList;

Movie({this.id, this.movieName, this.director, this.actorList});

factory Movie.fromJson(Map<String, dynamic> parsedJson){

 var actorArray = parsedJson[‘actors’] as List;
  List<Actor> actors = actorArray.map((e) => Actor.fromJson(e)).toList();

   return Movie(
      id: parsedJson[‘id’],
      movieName: parsedJson[‘movie_name’],
      director: Director.fromJson(parsedJson[‘director’]),
      actorList: actors
    );
  }
}

4. Parse JSON String Having String Array

We can easily parse the JSON into a Dart array without the need of creating any class.

String arrayText = {“visited_state”: [“MP”, “MH”, “RJ”, “GJ”]};
var stateJson = jsonDecode(arrayText)[‘visited_state’];
List<String> states = stateJson != null ? List.from(stateJson) : null;
print(states);

It will print the array:

[MP, MH, RJ, GJ]

Voila, Now you are able to parse any kind of JSON. Once you know the basics you will find it easy to parse any JSON.

For complex JSON we need to write more code in PODO and sometimes we find it a tedious task to write all this. So here is a solution available for this:

https://app.quicktype.io/
https://javiercbk.github.io/json_to_dart/

You need to paste your JSON String in the left panel and  it will generate the complete code for your PODO. How easy it is 🙂

But I suggest you create PODO by yourself when you are new to JSON parsing in Dart. It will help you to learn things easily.

Thank you for reading. Hope you find it useful.

Would love to see your comments in the blog!

Get started with Bloom