Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

dart
json
communitycreator

How to convert an object to JSON string in dart

Maria Elijah

Overview

To convert an object to JSON string, we use the jsonEncode method.

jsonEncode() is a built-in top-level function in the dart: convert library that can convert several types of objects to JSO strings.

There are three steps involved in converting an object to a JSON string:

  1. Create a class.
  2. Create toJson() method. This method returns a JSON object with key/value pairs for all of the class’s fields.
  3. Using the jsonEncode() function, extract a JSON string from a JSON object.

Implementation

Create a class named Student with the following attributes:

  • name
  • id
  • age
  • department
  • level
class Student{
  String name;
  String id;
  int age;
  String department;
  String level;

  Student(this.name, this.id, this.age, this.department, this.level);
}

Next, create a toJson() method:

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

If jsonEncode() function is called without creating toJson() method, an error will be thrown.

Finally, convert the Student object to a JSON string using the dart:convert library’s built-in jsonEncode() function:

String jsonStu = jsonEncode(student);

Let’s bring all these pieces of code together to see the output:

import 'dart:convert';

class Student{
  String name;
  String id;
  int age;
  String department;
  String level;

  Student(this.name, this.id, this.age, this.department, this.level);

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


main() {
  Student student = Student('Maria', '15AF132091', 23, 'Computer science', '400');

  String jsonStu = jsonEncode(student);
  print(jsonStu);
}

RELATED TAGS

dart
json
communitycreator
RELATED COURSES

View all Courses

Keep Exploring