JSON Serialization in Flutter

Updated 1 May 2023

Save

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.

You may also check our flutter app development services

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.

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home