JSON Serialization In Dart/Flutter With Built_Value

In this post, we will learn about JSON serialization in Dart/Flutter with Built_Value library. We will setup a serializer and see it in action.

Introduction

We have already covered introduction to built_value and it’s implementation detail in our previous posts. Now we are ready to jump into JSON serialization in dart/flutter with the built_value library.

As we have mentioned previously, Dart does not have good support for JSON serialization. You have to write quite a bit of code for every object that you wish to Serialize and De-serialize. This is where the power of Built Value types kick in.

Setup Serializers In Dart/Flutter With Built_Value

There are basically two steps to enable Serialization support for Built Value models:

  • Add a static Serializer in your model definition.
  • Define a top level Serializer that holds serializers for each of your models.

Create Built Value Type Model

Using the same Contact model from our previous post, let’s setup serialization. Add a static serializer to your model like this:

Complete code for Contact Model:

After adding the serializer, regenerate the ‘contact.g.dart‘.

You will notice that our generated model now has a serializer.

JSON Serialization In Dart
JSON Serialization In Dart

Create Top-Level Serializer For All Models

Next, add a new file called “serializers.dart”.

You can notice that it is again a multi-part file. The attribute @SerializersFor holds an array of built value types. It also has an instance of the default serializer.

The default serializer can be extended to add any number of other serializers using the builder pattern. More on that later.

Next, run the build_runner build command again to generate file ‘serializers.g.dart‘.

Become A Flutter Expert With This Course

Serialization In Action

To see things in action, let’s test our first serializer.

The code above will output a serialized array of values which looks like Dart’s primitive data types.

Adding JSON Serialization With Built_Value

Let’s add JSON serialization to the Contact built value type. Adjust your serializer as follows and regenerate the auto generate code.

We have added the “StandardJsonPlugin” plugin in the default serializer’s implementation. Now when we run the same code as before:

We will get a JSON format output.

Wrapping Up

In this post we looked at how we can setup JSON serialization in Dart/Flutter with built_value library. We continued from our previous post and added a basic serializer to our built value model.

Next, we will look at JSON Serialization and De-Serialization in more detail.

About the author