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:
toJson()
method. This method returns a JSON object with key
/value
pairs for all of the class’ fields.jsonEncode()
function, and extracting a JSON string from a JSON object.We will 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, 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