How can we convert an object to a JSON string in dart?
Overview
We will use the jsonEncode method to convert an object to a JSON string.
The jsonEncode() method is an in-built, top-level function in the dart: convert library, which can convert several types of objects to JSON strings.
There are three steps involved in converting an object to a JSON string:
- Creating a class
- Creating a
toJson()method. This method returns a JSON object withkey/valuepairs for all of the class’ fields. - Using the
jsonEncode()function, and extracting a JSON string from a JSON object.
Implementation
We will create a class named Student with the following attributes:
nameidagedepartmentlevel
class Student{
String name;
String id;
int age;
String department;
String level;
Student(this.name, this.id, this.age, this.department, this.level);
}
Next, we will create a toJson() method:
Map toJson() => {
'name': name,
'id': id,
'age': age,
'department': department,
'level': level
};
Note: If the
jsonEncode()function is called without creating atoJson()method, an error will be thrown.
Finally, we will convert the Student object to a JSON string, using the dart:convert library’s in-built jsonEncode() function:
String jsonStu = jsonEncode(student);
Now, 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);}
Free Resources
Copyright ©2026 Educative, Inc. All rights reserved