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

{
  "id" : 1,
  "name" : "vishwesh",
  "languages" : [ "dart", "java", "js", "python", "c++"],
  "mail" : "xyz@gmail.com",
  "gender" : "male",
  "about" : "SDE"
}

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

#flutter #json #developer

JSON Serialization in Flutter with built_value library
6.80 GEEK