dart-convert-object-json-feature-image

Dart/Flutter – Convert Object, List to JSON string

In this Dart/Flutter JSON encode tutorial, I will show you ways to convert Object, Nested Object, List, List of JSON objects into JSON string. Finally, you can convert a complex Nested Object (that contains some fields and a List of objects field) into JSON string.

Related Post: Dart/Flutter – Convert/Parse JSON string, array into Object, List


Overview

dart:convert library provides a built-in top-level function called jsonEncode that can convert many types of Object to JSON string.

We have 3 steps to convert an Object/List to JSON string:

  • create the class
  • create toJson() method which returns a JSON object that has key/value pairs corresponding to all fields of the class
  • get JSON string from JSON object/List using jsonEncode() function

For every type of Object, Nested Object, simple List, List of Objects, or Nested Object containing List, we will implement toJson() method with some little difference.

Dart/Flutter convert simple Object to JSON string

Assume that we have a User class with fields: name & age.

class User {
  String name;
  int age;

  User(this.name, this.age);
}

If you call jsonEncode() function without creating toJson() method. You will get an error:

Unhandled exception:
Converting object to an encodable object failed: Instance of 'User'
...

Let’s create toJson() method like the following code:

class User {
  String name;
  int age;

  User(this.name, this.age);

  Map toJson() => {
        'name': name,
        'age': age,
      };
}

Now we can use dart:convert library’s built-in jsonEncode() function to convert the User object to JSON string:

import 'dart:convert';

main() {
  User user = User('bezkoder', 21);

  String jsonUser = jsonEncode(user);
  print(jsonUser);
}

The result will show a string like this.

{"name":"bezkoder","age":21}

Dart/Flutter convert Nested Object to JSON string

If we have a Tutorial class and author is a field that has User class type.
We’re gonna create toJson() method with the author is the result when calling User‘s toJson() method.

class User {
  String name;
  int age;
  ...
}

class Tutorial {
  String title;
  String description;
  User author;

  Tutorial(this.title, this.description, [this.author]);

  Map toJson() {
    Map author =
        this.author != null ? this.author.toJson() : null;

    return {'title': title, 'description': description, 'author': author};
  }
}

Remember to check if author property is null or not.
Now we can easily call jsonEncode() like this.

import 'dart:convert';

main() {
  User user = User('bezkoder', 21);
  Tutorial tutorial = Tutorial('Dart Tut#1', 'Tut#1 Description', user);

  String jsonTutorial = jsonEncode(tutorial);
  print(jsonTutorial);
}

Check the result, you can see our JSON string:

{"title":"Dart Tut#1","description":"Tut#1 Description","author":{"name":"bezkoder","age":21}}

Dart/Flutter convert List to JSON string

We can easily do JSON encode a List without the need of creating any class.

import 'dart:convert';

main() {
  List<String> tags = ['tagA', 'tagB', 'tagC'];
  String jsonTags = jsonEncode(tags);
  print(jsonTags);
}

The result shows a JSON string array:

["tagA","tagB","tagC"]

Dart/Flutter convert List of objects to JSON string

How about more complicated List? For example, every item in the List is a Tag object.
The Tag class has 2 fields: name & quantity. So we also need to create toJson() method that return a Map.

class Tag {
  String name;
  int quantity;

  Tag(this.name, this.quantity);

  Map toJson() => {
        'name': name,
        'quantity': quantity,
      };
}

Now everything becomes simple with jsonEncode() function.

import 'dart:convert';

main() {
  List<Tag> tags = [Tag('tagA', 3), Tag('tagB', 6), Tag('tagC', 8)];
  String jsonTags = jsonEncode(tags);
  print(jsonTags);
}

JSON string looks like an array:

[{"name":"tagA","quantity":3},{"name":"tagB","quantity":6},{"name":"tagC","quantity":8}]

Dart/Flutter convert complex Nested Object to JSON string

Yeah! You’re in the last section of this tutorial.
We will convert a complex Nested Object that contains some fields and a List of objects field into JSON string.

For example, Tutorial class has title, description, author (User class), tags (List<Tag>):

class Tutorial {
  String title;
  String description;
  User author;
  List<Tag> tags;

  Tutorial(this.title, this.description, [this.author, this.tags]);
}

We’re gonna define the toJson() method like this:

class Tutorial {
  ...
  Map toJson() {
    Map author =
        this.author != null ? this.author.toJson() : null;

    List<Map> tags =
        this.tags != null ? this.tags.map((i) => i.toJson()).toList() : null;

    return {
      'title': title,
      'description': description,
      'author': author,
      'tags': tags
    };
  }
}

In the constructor method, we set author and tags optional.
So when initializing a Tutorial, we don’t need to pass these fields as parameters.

We use map on tags property to return the JSON object. Then, convert the map result to a List of JSON object using toList() method.

Our main() function will be like this.

import 'dart:convert';

main() {
  User user = User('bezkoder', 21);
  String jsonUser = jsonEncode(user);
  print(jsonUser);

  List<Tag> tags = [Tag('tagA', 3), Tag('tagB', 6), Tag('tagC', 8)];
  String jsonTags = jsonEncode(tags);
  print(jsonTags);

  Tutorial tutorial = Tutorial('Dart Tut#2', 'Tut#2 Description', user, tags);
  String jsonTutorial = jsonEncode(tutorial);
  print(jsonTutorial);
}

Let’s check the result in console, you will see the JSON string.

{"title":"Dart Tut#2","description":"Tut#2 Description","author":{"name":"bezkoder","age":21},"tags":[{"name":"tagA","quantity":3},{"name":"tagB","quantity":6},{"name":"tagC","quantity":8}]}

If we don’t initialize Tutorial with author and tags as the following code.

import 'dart:convert';

main() {
  Tutorial tutorial = Tutorial('Dart Tut#3', 'Tut#3 Description');
  String jsonTutorial = jsonEncode(tutorial);
  print(jsonTutorial);
}

This is the result:

{"title":"Dart Tut#3","description":"Tut#3 Description","author":null,"tags":null}

Conclusion

That’s how we convert many kind of Objects and List to JSON string in Dart/Flutter. One of the most important part to make our work simple is the dart:convert library‘s built-in jsonEncode() function.

You can find way to convert in the opposite way at:
Dart/Flutter – Convert/Parse JSON string, array into Object, List

Happy Learning! See you again.

Further Reading

3 thoughts to “Dart/Flutter – Convert Object, List to JSON string”

  1. Hello, interesting your article, I see that the code is more optimized, when you write

    Map toJson() => {
       'name': name,
       'quantity': quantity,
    };
    

    something different from this:

    Map toJson() {
        final Map data = new Map();
        data['maximum'] = this.maximum;
        data['minimum'] = this.minimum;
        return data;
      }
    

    That’s why I say that it is optimized,

    but in your previous article, about jsonDecode I don’t see that it’s optimized, or simplified code
    https://bezkoder.com/dart-flutter-parse-json-string-array-to-object-list/
    I don’t know if you could tell me how to do it, or edit your jsonDecode article to see an improved code.

    I don’t know if you understand what I say,

    well, I’m learning from your articles,

    thanks

    1. Hi, I don’t really understand your idea. But I can say that, when you decode, you need type safe.
      That’s why it is more complicated than encoding toJson(). 🙂

Leave a Reply

Your email address will not be published. Required fields are marked *