JSON Serialization in Flutter using json_serializable

JSON (JavaScript Object Notation) is a text based representation in the JavaScript Object format and is widely used in REST API. As a application developer it is always boring to parse the each fields of the objects manually. Hence JSON serialization comes there which make the developer life easy by taking care of itself.

I assumed you have the basic idea of JSON encoding and decoding before starting this tutorial. JSON encoding is the process of converting JSON equivalent Map object to plain string whereas JSON decoding is opposite. So basically JSON decoding is done to convert plain string into modal and encoding is used to send request.

For the dummy API, lets take sample response from https://my-json-server.typicode.com/yubarajpoudel/xaapp/posts

In order to map the response let create the model from this Post.dart

class Post{
  int? userId;
  int? id;
  String? title;
  String? body;
}

Decoding response as a map without using json_serializable

Here is the common way of creating the map

paste the JSON Object response in https://jsontodart.com/

 

 

Using json_serailizable

In pubspec.yaml paste the following dependency

  json_serializable: ^6.1.4

 

 

 

 

 

 

JSON serializable use the annotation to parse the JSON response and map with class fields. for more information see this link https://pub.dev/packages/json_serializable

import 'package:flutter/cupertino.dart';
import 'package:json_annotation/json_annotation.dart';
part 'post.g.dart';

@JsonSerializable()
class Post{
int? userId;
int? id;
String? title;
String? body;

@JsonKey(ignore: true)
List<Post>? postList;
@JsonKey(ignore: true)
String? errorMessage;
Post();


Post.init(this.userId, this.id, this.title, this.body);

factory Post.fromJson(Map<String, dynamic> json) => _$PostFromJson(json);

Map<String, dynamic> toJson() => _$PostToJson(this);
}

The main annotation used to serialize using json_serializable is  JsonSerializable. When applied to a class toJson and fromJson code will be generated when you build. There are three ways to control how code is generated:

  1. Setting properties on JsonKey annotating the target field.
  2. Set properties on JsonSerializable annotating the target type.

post.g.part this will be auto generated . To generate this add the following dependencies in pubspec.yaml.

    build_runner: ^2.1.1

After adding fetch the dependencies by entering following command.

flutter pub get

Now create the build file using following command in terminal.

flutter pub run build_runner build

Leave a Reply

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