Chrome Extension

Converting class objects to JSON string in Flutter

class Employee {
  final String name;
  final String email;

  Employee(this.name, this.email);

  Employee.fromJson(Map<String, dynamic> json)
      : name = json['name'],
        email = json['email'];

  Map<String, dynamic> toJson() =>
    {
      'name': name,
      'email': email,
    };
}

//Now CONVERT SIMPLE JSON TO FLUTTER OBJECT 
Map employeeMap = jsonDecode(jsonString);
var employee = Employee.fromJson(employeeMap);

//CONVERT FLUTTER OBJECT TO SIMPLE JSON STRING
String json = jsonEncode(employee);
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place. Check how cool is the tool

Remember that there must be 'Map<String, dynamic> toJson()' function if you want to convert flutter class object to JSON string. You can return an object from it like simple JSON objects. 

Was this helpful?
0 Comments
Join Devsheet Ask a Question