How to convert Objects to JSON string in Dart/Flutter ?

how-to-convert-dart-object-to-json-string-featured

Converting dart object to json string is not so easy as like other programming languages in my point of view.

Converting Dart Object to JSON string

Sample Dart class

class Options with ChangeNotifier{   
    String key;
    String point;
    bool checked;

    Options({this.key, this.point, this.checked});
}

Issue when you do jsonEncode(options)

════════ Exception caught by gesture ═══════════════════════════════════════════
Converting object to an encodable object failed: Instance of 'Options'
════════════════════════════════════════════════════════════════════════════════

How to fix “Converting object to an encodable object failed: ” Instance of ‘Options’ exception in Dart/Flutter?

import 'package:flutter/cupertino.dart';

class Options with ChangeNotifier{   
    String key;
    String point;
    bool checked;

    Options({this.key, this.point, this.checked});

    Map toJson() => {
      'key':key,
      'point':point,
      'checked':checked
    };
    
}

jsonEncode(options) after toJson() implementation

I/flutter (27115): {"key":"Less than 7hrs","point":"2","checked":true}

Wow! we got it! right!!

How to convert List of Nested object to JSON string ?

Class with list of nested object

Here, you can see the Task class has the List of details object. Now just follow the Task and the Details class below to learn how to do the nested list of object to json string.

class Task {  
  String name;
  String category;
  String status;
  String desc;
  List<Details> details;
}

Converting list of nested object to json string

Here details is the list of nested obect which needs to be converted to json string. So I am iterating and calling the toJson method of the detaills object.

Map toJson() {
    List<Map> details = this.details != null ? this.details.map((i)=> i.toJson()).toList() : null;
    return {
      'name': name,
      'Category': category,
      'status': status,
      'desc': desc,
      'details': details
    };
  }  

Nested object – toJson Method

Again this has some list of objects, then same way it continous for nested inside nested objects also.

class Details {
  String type;
  String label;
  String name;
  List<Options> options;
  String value;
  String image;
  int order;
  String taskTip;

Map toJson() { 
    List<Map> options = this.options ==null?null : this.options.map((e) => e.toJson()).toList();
    return { "type":type,
    "label":label,
    "name":name,
    "options":options,
    "value":value,
    "image":image,
    "order":order,
    "taskTip":taskTip,
  };
  }
}

Important Note:

If you have some 10 fields or variables or class properties in your Dart class and you want only few to be converted to json then just add only those required fields to your “Map toJson()” method.

Leave a Reply