Working with JSON in Flutter

Vishwesh Soni
Aubergine Solutions
3 min readJan 21, 2020

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 only works for a limited scope. The developer has to work on each class and write a function for serialization and deserialization of JSON every time. At the production level Manual Serialization becomes a tedious and time-consuming task, robbing the developer of productive working hours.

2) Automated serialization(built_value):

For this instance, we will be working with the built_value library- created by David Morgan, a software engineer at Google.

Let’s work this through with the following example:

Sample.json

Step 1: Add dependencies to pubspec:

pubspec.yaml
pubspec.yaml

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

You can use the JSON to Dart built_value class converter, to create classes according to the JSON you provide. Next, give an appropriate name to your JSON. I’m going to work with UserModel as a class name.

Step 3: Add models directory:

Folder Structure

The project structure is as shown:

---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.dartlibrary 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

Now this snippet will generate code only once. In case you want a continuous code generator then run the command below

flutter packages pub run build_runner watch

At this point your classes will be ready to work with your APIs.

Step 7: Output:

To check whether your code is working or not, you can do as shown below.

// 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.

For more about programming, follow me and Aubergine Solutions, so you’ll get notified when we write new posts.

Have any questions feel free to reach out to me!

--

--