How to convert JSON data to Dart Models?

How to convert JSON data to Dart Models?

Introduction

Today, we will see how we can convert JSON data to Dart models. It is a very important thing to do when you are working with data coming from the internet. There are services that convert your JSON data to dart models with just a single click but it is very important to understand the actual logic behind it.

So without wasting any time, let's get started.

What is JSON data and Dart Models

First of all, let me explain what a JSON object is. JSON is basically a map that stores key-value pairs. Here is an example of a JSON object.

{
"text": "39 is the traditional number of times citizens of Ancient Rome hit their slaves when beating them, referred to as "Forty save one".",
"number": 39,
"found": true,
"type": "trivia"
}

Dart Model is a class that stores this JSON object in a systematic way. We do this because directly accessing the JSON object in your UI code can lead to unhandled null-check errors. It becomes very tricky to find out where the exact error is if you do not use the JSON to dart conversion.

It is also difficult to access any key value because you have to remember the spelling of the key and all that stuff.

Let's make a model that converts the above JSON object into a Dart model.

Coding the Logic

First of all, create a class named NumberTrivia. In that class, add 4 variables named text, number, found, and type. Create a constructor that needs all these 4 variables and make it required.

We keep it required because suppose we didn't receive the found key then we will quickly know in the error logs about it.

class NumberTrivia {
 String text;
 int number;
 bool found;
 String type;

 NumberTrivia({
  required this.text,
  required this.number,
  required this.found,
  required this.type,
});

Next, we will need two functions.

  1. fromJSON
  2. toJSON

As the name suggests, fromJSON will convert the data from a JSON object to the model and toJSON will convert our data back to a JSON object.

For the fromJSON method, we will use the factory method. What is a factory method? The factory method is like a constructor but it is used instead of a constructor because the constructor creates a new instance of the class every time it is called.

For a detailed guide on what a factory method is, go check out this answer..

    factory NumberTrivia.fromJson(Map<String, dynamic> json) => NumberTrivia(
        text: json["text"],
        number: json["number"],
        found: json["found"],
        type: json["type"],
    );

The code is self-explanatory. I have created an instance of Number Trivia which needs a JSON object as an input. If you want to convert the above JSON object to a NumberTrivia model then just call this fromJSON function like this.

var jsonBody = {
"text": "39 is the traditional number of times citizens of Ancient Rome hit their slaves when beating them, referred to as "Forty save one".",
"number": 39,
"found": true,
"type": "trivia"
}

// myModel stores the Model received by the fromJSON method.
TriviaModel myModel = TriviaModel.fromJSON(jsonBody);

print(myModel.number) // prints 39
print(myModel.found) // prints true

This is how we convert a JSON to a dart model. It was pretty simple right. Now let's look at toJSON method.

Here is the code for toJSON method

Map<String, dynamic> toJson() {
return  {
        "text": text, 
        "number": number,
        "found": found,
        "type": type,
    };
}

We don't need any parameters here. We return a Map of string and dynamic since JSON is a map of String and dynamic.

Here is the code for the complete NumberTrivia class.

import 'dart:convert';

class NumberTrivia {
    NumberTrivia({
        required this.text,
        required this.number,
        required this.found,
        required this.type,
    });

    String text;
    int number;
    bool found;
    String type;

    factory NumberTrivia.fromJson(Map<String, dynamic> json) => NumberTrivia(
        text: json["text"],
        number: json["number"],
        found: json["found"],
        type: json["type"],
    );

    Map<String, dynamic> toJson() => {
        "text": text,
        "number": number,
        "found": found,
        "type": type,
    };
}

Bonus Tip

If you followed till here and tried out the above code example then great, you have learned how the whole model thing actually works. The example that we used was a very easy one and generally, data coming from third-party APIs are not so simple. There are many APIs that return some real complex JSON objects. One of them is this api

If you start writing the model class for such JSON objects, it will take hours of your time. So instead of doing this monotonous work, we work smartly by using quicktype.io.

All you need to do is copy the whole JSON object and paste it on this website. Within a second, you will get the whole Dart model. Great, isn't it?

Conclusion

So today, we learned how you can convert the JSON objects into Dart models and vice versa. Even though there is a service that does this for free, it is important to understand how things work. It is a fundamental concept and you should know it if you are a Flutter developer.

You can appreciate and support my blogs via.

https://cdn.hashnode.com/res/hashnode/image/upload/v1646372265341/O0KkM6E-0.png

Also, let's connect on Twitter. Follow CSwithIyush for more amazing tutorials, tips/tricks on Flutter & DSA.

Did you find this article valuable?

Support Ayush Pawar by becoming a sponsor. Any amount is appreciated!