Dart Convert List as Map Entry for JSON Encoding

2020-07-10 07:45发布

I asked a question before about Dart encoding/decoding to JSON, however, the libraries that were suggested were not complete and I decided to manually handle that.

The objective is to convert these objects to a map.

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

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

When doing

print(JSON.encode(parent.toMap()));

I am seeing it go here, any suggestion how to make this work?

if (!stringifyJsonValue(object)) {
  checkCycle(object);
  try {
    var customJson = _toEncodable(object);
    if (!stringifyJsonValue(customJson)) {
      throw new JsonUnsupportedObjectError(object);
    }
    _removeSeen(object);
  } catch (e) {
    throw new JsonUnsupportedObjectError(object, cause : e);
  }
}
}

标签: dart
3条回答
冷血范
2楼-- · 2020-07-10 08:24

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,
      };
}
查看更多
够拽才男人
3楼-- · 2020-07-10 08:38

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};   
}
查看更多
放荡不羁爱自由
4楼-- · 2020-07-10 08:39
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

查看更多
登录 后发表回答