Dart Convert List as Map Entry for JSON Encoding

Map toMap() => {"id":id, "name":name: "listChild": listChild.map((c) => c.toJson().toList())};

is valid for JSON.

import 'dart:convert' show JSON;

...

String json = JSON.encode(toMap());

You can also use the toEncodeable callback - see How to convert DateTime object to json


Just rename Map toMap() into Map toJson() and it will work fine. =)

void encode() {
    Parent p = new Parent();
    Child c1 = new Child();
    c1 ..id = 1 ..childName = "Alex";

    Child c2 = new Child();
    c2 ..id = 2 ..childName = "John";

    Child c3 = new Child();
    c3 ..id = 3 ..childName = "Jane";

    p ..id = 1 ..name = "Lisa" ..listChild = [c1,c2,c3];

    String json = JSON.encode(p);
    print(json);
}

class Parent extends Object {
    int id;
    String name;
    List<Child> listChild = new List<Child>();
    Map toJson() => {"id":id, "name":name, "listChild":listChild};
}

class Child extends Object {
    int id;
    String childName;
    Map toJson() => {"id":id, "childName":childName};   
}

If your class structure does not contain's any inner class then follow

class Data{

  String name;
  String type;

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

If your class uses inner class structure

class QuestionTag {
  String name;
  List<SubTags> listSubTags;

  Map<String, dynamic> toJson() => {
        'name': name,
        'listSubTags': listSubTags.map((tag) => tag.toJson()).toList()
      };
}

class SubTags {
  String tagName;
  String tagDesc;

  SubTags(this.tagName, this.tagDesc);

  Map<String, dynamic> toJson() => {
        'tagName': tagName,
        'tagDesc': tagDesc,
      };
}

Tags:

Dart