Parsing JSON Like Pro in Flutter

Mark
By -
0

 

parsing-json-like-pro-in-flutter


Parsing JSON is a very common task in flutter application development. It is either the app will have to communicate to an external API to fetch JSON data or have to parse a local JSON data. In the article, I will cover the basic and advance ways of parsing JSON in flutter.

After reading this article you will be comfortable with working with simple and complex JSON data in flutter.

Simple Json Structure

A sample of a very simple JSON data that we can receive from a server into a flutter app in this:

 "id": 500987, 
 "name":"Mark", 
 "age":30, 
 "job":"Software Developer" 
}

Let's try to work with the above JSON object and retrieve just the name value in dart.

Create a variable and assign the JSON object like so:

var personJson = '{id: 500987,"name":"Mark","age":30,"job":"Software Developer"}'; print(personJson);

The result of the print statement should look like this:

{id: 500987,"name":"Mark","age":30,"job":"Software Developer"}

The result is almost identical to the variable itself except that it was printed without the single quote in the beginning and the end. And this is just like a map in dart and therefore we may think that it should be very easy to get any value out of the map with the key - for example let's try to get the name by writing this:

print(personJson["name"]);

This will result in an error that look like this

Error compiling to JavaScript: main.dart:7:20: Error: A value of type 'String' can't be assigned to a variable of type 'int'. print(personJson["name"]);

The dart:convert library

To make JSON serialization in Flutter a very simple task, Dart has a built-in dart:convert library that includes a straightforward JSON encoder and decoder.

There are two ways in which this JSON can be serialized with dart:convert - Inline and in Model Classes.

Serialize the Inline way

It is very easy to convert the JSON object into a map by calling the jsonDecode function that dart:convert offer. The first step is to import the dart:convert and then call the required function and pass in the JSON string as a method argument.

We know that Dart is statically typed language and wherever possible we will like to add types to all the data that we are working with, in the case jsonDecode function returns  Map<String,dynamic>, which simply mean that we can't figure out the types at design time until runtime. Serializing the model classes way resolves this issue.

Serialize the Model Classes way

To solve the problem of not knowing the data type we are working with mentioned previously, we will create a model class that will represent the JSON object.

Looking at the JSON structure, we have id and age of int type, while others are of String type. Create a class named person like so


Now we can update our previous code like this:


Now we can access the properties easily without square bracket, and Dart now have a better idea about the data types we are working on.

However, this approach is still error prone, take a look at the point when we create an instance of the class.

var typedResult = Person(decodedJson["id"],decodedJson["name"],decodedJson["age"],decodedJson["job"]);

We still have to manually add decodedJson["id"]. Let make the class instance creation more better. Instead of doing this any time we instantiate the person class, it is better we do this within the class itself. That means we can just pass the parsedJson to the class and let the class process it. Like this:

Changing this:
var typedResult = Person(decodedJson["id"],decodedJson["name"],decodedJson["age"],decodedJson["job"]);
To this
var typedResult = Person.fromJson(decodedJson);

Let's add a named constructor to our class where all the conversion will be done. Add the following code below the class main constructor:

Person.fromJson(Map json) { 
 id = json['id']; 
 name = json['name']; 
 age = json['age']; 
 job = json['job'];
}

The full code will now look like this:


It is now much easier to parse the JSON object into a typed model class in our dart project.

And that's it for this tutorial. I know it may not be the best JSON parsing article out there, (because I’m still learning a lot) but I hope it got you started.

Post a Comment

0Comments

Post a Comment (0)