JSON Serialization in Flutter with built_value library

JSON(JavaScript Object Notation)

JSON is a format that encodes the object in a String.

Serialization

It is a process of turning any data structure into a String.

While working with APIs(Application Programming Interface) it is hard to handle JSON response at the front-end. In Flutter we can do it with two methods

  1. Manual serialization
  2. Automated serialization using code generation

1) Manual serialization:

Manual Serialization works for a limited scope only. Every time the developer has to work on each and every class and write a function for serialization and deserialization of JSON and it’s not productive work because when it comes to production level it becomes a time-consuming process.

2) Automated serialization(built_value):

We will work with the built_value library which is created by David morgan a software engineer at Google.

Let’s Work with one Example

Sample.json

Step 1: Add dependencies to pubspec:

pubspec.yaml

pubspec.yaml

Step 2: Use a tool for converting JSON to Dart :

The JSON to Dart built_value class converter. It will create classes for you according to the JSON you provide. Give an appropriate name to your JSON. Here we will give UserModel as a class name.

Step 3: Add models directory:

Folder Structure

You can see the project structure:

---android                            
---ios
---lib
   --models//add this dir.      
   -main.dart
---test
---web

Step 4: Create Classes:

Add classes in the models directory.

  • Add Model class in the models directory
  • Add serializer class in the models directory
  • Paste the code which is generated by the tool in the model(user_model.dart in our example) class
//Structure
---Android
---ios
---lib
   --models
     -user_model.dart   //model class
     -serialzers.dart   //serializer class
   -main.dart
---test
---web

Step 5: Add serializers.dart in the models directory:

library serializers;
part 'serializers.g.dart';
@SerializersFor(const [
  UserModel,  //add your different model classes
])
final Serializers serializers =
(_$serializers.toBuilder()..addPlugin(StandardJsonPlugin())).build(

Note: Make sure your file name matches with the part.

E.g. part ‘user_model.g.dart’ and file name : user_model.dart

File-Name : user_model.dart
library user_model;

import 'dart:convert';

import 'package:built_collection/built_collection.dart';
import 'package:built_value/built_value.dart';
import 'package:built_value/serializer.dart';
import 'package:medium_built/models/serializers.dart';

part 'user_model.g.dart';//make sure name of part == filename

abstract class UserModel implements Built<UserModel, UserModelBuilder> {
  UserModel._();

  factory UserModel([updates(UserModelBuilder b)]) = _$UserModel;

  @BuiltValueField(wireName: 'id')
  int get id;
  @BuiltValueField(wireName: 'name')
  String get name;
  @BuiltValueField(wireName: 'languages')
  BuiltList<String> get languages;
  @BuiltValueField(wireName: 'mail')
  String get mail;
  ......
  ......
 Note: Keep only one part '*.g.dart' remove other part from the code       

Step 6: Generate parts:

flutter packages pub run build_runner build

It will generate code only once. If you want continuous code generator then run below command,

flutter packages pub run build_runner watch

Now your classes are ready to work with your APIs.

Step 7: Output:

If you want to check your code is working or not, you can do something like this.

// add _runcode method in sample flutter app 
floatingActionButton: FloatingActionButton(
  onPressed: _runcode,
  child: Icon(Icons.add),
)
//method
void _runCode() {
    UserCode.runCode();
}
//UserCode class
import 'package:medium_built/models/user_model.dart';

class UserCode{
    static runCode(){
      var user_details= UserModel((u)=> u..id=1
        ..name="Vishwesh"
        ..mail="ztr@gmail.com"
        ..gender="Male"
      );
    print(user_details);
    }
}

Thanks for reading.