How to Convert JSON into Class objects in Dart

How to Convert JSON into Class objects in Dart

Learn how to convert JSON into class objects in Dart as well as parse JSON into nested classes, something often needed for API calls.

When working with small amounts of data, often it’s fairly easy to extract desired values from JSON objects. However, once we begin working with large datasets and large response objects from API calls, our JSON can become very difficult to parse into our desired class objects. This article shows you how to convert JSON into class objects as well as parse JSON into nested classes, something often needed for API calls.

The Data:

For this example, let's assume that my data looks something like this:

{     
    "type": "articles",     
    "id": "1",    
    "data": [
        "val",
        "val2"
    ],
    "author": {
        "id": "42", 
        "name": "bo"
    }   
}

This data object is rather simple but will help us highlight all the important cases that we care about.

Our Classes:

In this example, we have 2 classes that we are working with: Document.dart

class Document {
    final String type;
    final int id;
    final List<String> data;
    final Author author;    Document({this.type, this.id, this.data, this.author});    // add fromJson method here
}

and our Author.dart

class Author{
    final int id;
    final String name;    Author({this.id, this.name});    // add fromJson method here
}

FromJson Methods:

Let’s first start with our Author class as it has no nested class objects in it.

class Author{
    final int id;
    final String name;    Author({this.id, this.name});    factory Author.fromJson(Map<String, dynamic> json) {
        return Author(
            id: json["id"],
            name: json["name"],
        );
    }
}

As you can see, it’s a rather simple method when you are dealing with just converting simple variables from JSON into your class objects. To ensure we don’t have any issues with the format in which the data is received from our APIs, you can go a step further and cast the JSON values into your object type like so:

json["name"].toString()

This is not necessary, but sometimes useful if the source of the API is not reliable or a professional service. I’ve seen instances in the past where when a double is equal to 0, the JSON object reads it as an int instead of a double which then throws an error. Casting your value into a variable type is a safe way of handling those rare cases.

Next, let’s take a look at our parent class, Document:

class Document {
    final String type;
    final int id;
    final List<String> data;
    final Author author;    Document({this.type, this.id, this.data, this.author});factory Document.fromJson(Map<String, dynamic> json) {
        var dataObj = json['data'];        return Document(
            type: json["type"],
            id: json["id"],
            data: new List<String>.from(dataObj),
            author: Author.fromJson(json['author']),
        );
    }
}

Notice how there are two new types of values that we are working within our Document class:

  1. We have a list of a type of variable. We cannot just immediately assign the JSON value to the list because it will take on the form of a List <dynamic> object instead of a List <String> object. So we first need to create a List <dynamic> object and then cast it into a List <String> object using the “from” method.
  2. The second new type of value we are working with is a child class object. Because we already defined that objects “fromJson” method, however, we simply need to call that fromJson method and let it do the rest of the parsing. You can keep nesting Class objects this way until you have all of the data that you need.

dart json flutter mobile-apps programming

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Google's Flutter 1.20 stable announced with new features - Navoki

Google has announced new flutter 1.20 stable with many improvements, and features, enabling flutter for Desktop and Web

Top 25 Flutter Mobile App Templates in 2020

Flutter has been booming worldwide from the past few years. While there are many popular mobile app development technologies out there, Flutter has managed to leave its mark in the mobile application development world. In this article, we’ve curated the best Flutter app templates available on the market as of July 2020.

Flutter App Development Trends 2020

As the new decade dawns upon us, a slew of technologies has been making a lot of noise to grab the developers’ attention. While native app development is going strong, the trade winds are now blowing towards going cross-platform.

How To Succeed In Mobile App Wireframe Design?

This article covers everything about mobile app wireframe design: what to do and what not, tools used in designing a mobile or web app wireframe, and more.

What is Flutter and why you should learn it?

Flutter is an open-source UI toolkit for mobile developers, so they can use it to build native-looking Android and iOS applications from the same code base for both platforms. Flutter is also working to make Flutter apps for Web, PWA (progressive Web-App) and Desktop platform (Windows,macOS,Linux).