Dart将列表转换为JSON编码的映射条目



我之前问过一个关于Dart对JSON的编码/解码的问题,但是,建议的库并不完整,我决定手动处理。

目标是将这些对象转换为地图。

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};   
}

进行时

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

我看到它在这里,有什么建议如何让它发挥作用吗?

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);
  }
}
}
Map toMap() => {"id":id, "name":name: "listChild": listChild.map((c) => c.toJson().toList())};

对JSON有效。

import 'dart:convert' show JSON;
...
String json = JSON.encode(toMap());

您也可以使用toEncodeable回调-请参阅如何将DateTime对象转换为json

如果您的类结构不包含任何内部类,则遵循

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

如果您的类使用内部类结构

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,
      };
}

只需将Map toMap()重命名为Map toJson(),它就会正常工作。=)

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};   
}

相关内容

最新更新