Read now

JSON Serialization in Flutter

While developing mobile apps, communicating with the server to fetch or store data is the primary need of most of the mobile apps. One of the most popular format for the data transfer is JSON.

The most easy way is to parse the JSON manually. Manual decoding can be done using the built in JSON decoder in dart:convert. Using manual decoding requires the use of following function jsonDecode(). This function returns Map<String, dynamic> which can be parsed to read the required values.

Let’s see an example of manual JSON parsing with the following model:

Now to read the values of JSON we will use the function jsonDecode()

The another way of JSON serialization is by using code generation libraries. There are many libraries present but we will be using json_serializable, an automated source code generator that generates the JSON serialization boilerplate for you.

Setting up json_serializable in project for serialization

We need to add below dependencies in the pubspec.yaml file of your project.

Run flutter pub get inside your project root folder (or click Packages get in your editor) to make these new dependencies available in your project.

Creating Model class for JSON serialization

Let’s create a class name User with the file name as used.dart for an example:

Running the code generation utility

While creating json_serializable classes the first time, you may see the error as below image:

This is just a normal error which came just because currently generated code of the model class does not exist. To resolve this we just need to run the below command on terminal.

NOTE: You need run this command every time you make changes in your model class.

Using the model class

Finally, we need to know how we can use the model class in the our code. We just need to pass our JSON response and get the results.

Now we can use the model easily with more code safety.

 

. . .

Comment

Add Your Comment

Be the first to comment.

css.php
Hire Us!
Brief us about your requirements and we'll get back to you.
Woo! Hooy!
We have just recieved your project brief and our expert will contact you shortly.
Send Again
Close