Article

Working with JSON in Flutter

Last updated 
Jan 21, 2020
 min read
Episode 
 min
Published 
Jan 21, 2020
 min read
Published 
Jan 21, 2020
 min

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:

1library serializers;
2part 'serializers.g.dart';
3@SerializersFor(const [
4  UserModel,  //add your different model classes
5])
6final Serializers serializers =
7(_$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

1library user_model;
2
3import 'dart:convert';
4
5import 'package:built_collection/built_collection.dart';
6import 'package:built_value/built_value.dart';
7import 'package:built_value/serializer.dart';
8import 'package:medium_built/models/serializers.dart';
9
10part 'user_model.g.dart';//make sure name of part == filename
11
12abstract class UserModel implements Built<UserModel, UserModelBuilder> {
13  UserModel._();
14
15  factory UserModel([updates(UserModelBuilder b)]) = _$UserModel;
16
17  @BuiltValueField(wireName: 'id')
18  int get id;
19  @BuiltValueField(wireName: 'name')
20  String get name;
21  @BuiltValueField(wireName: 'languages')
22  BuiltList get languages;
23  @BuiltValueField(wireName: 'mail')
24  String get mail;
25  ......
26  ......

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.

1// add _runcode method in sample flutter app 
2floatingActionButton: FloatingActionButton(
3  onPressed: _runcode,
4  child: Icon(Icons.add),
5)
6//method
7void _runCode() {
8    UserCode.runCode();
9}
10//UserCode class
11import 'package:medium_built/models/user_model.dart';
12
13class UserCode{
14    static runCode(){
15      var user_details= UserModel((u)=> u..id=1
16        ..name="Vishwesh"
17        ..mail="ztr@gmail.com"
18        ..gender="Male"
19      );
20    print(user_details);
21    }
22}

Thanks for reading.

Also, have a look at this blog post that covers the basics of building a complex navigation stack using Flutter.

Authors

Vishwesh Soni

Software Engineer
I’m a software engineer with experience in developing scalable solutions. I focus on building efficient, scalable systems and love solving challenging technical problems. Constantly learning and exploring new tools, I’m committed to improving both my skills and the software I create.

Podcast Transcript

Episode
 - 
minutes

Host

No items found.

Guests

No items found.

Tags

No items found.

Have a project in mind?

Read