使用嵌套映射将 JSON 映射到对象

时间:2021-04-11 13:14:03

标签: json flutter mapping

我有一个由类别组成的 JSON 结构。这些类别可以有不同数量的节点,并且这些节点内部也有节点图。此 JSON 的示例结构如下所示:

[
   {
      "id":"category1",
      "name":"Piłka nożna",
      "nodes":[ 
        {
            "id":"node1",
            "name":"Bayern Monachium",
            "parentId":"category1",
            "nodes": [
                {
                    "id":"node12",
                    "name":"Robert Lewandowski",
                    "parentId":"node1",
                    "nodes": []    
                },
                {
                    "id":"node13",
                    "name":"Thomas Mueller",
                    "parentId":"node1",
                    "nodes": []                
                }
            ]
         },
         {
            "id":"node2",
            "name":"Hertha Berlin",
            "parentId":"category1",
            "nodes": []
         },
         {
            "id":"node5",
            "name":"Werder Brema",
            "parentId":"category1",
            "nodes": []
         }
      ]
   },
   {
      "id":"category2",
      "name":"Koszykówka",
      "nodes": []
   }
]

我编写了允许用对象表示这个 JSON 的类:

class Category {
  String id;
  String name;
  Map<String,Node> nodes;
  
  Category(String id, String name, Map<String,Node> nodes) {
    this.id = id;
    this.name = name;
    this.nodes = nodes;
  }
}

class Node {
  String id;
  String name;
  String parentId;
  Map<String, Node> nodes;
  
  Node(String id, String name, String parentId, Map<String, Node> nodes) {
    this.id = id;
    this.name = name;
    this.parentId = parentId;
    this.nodes = nodes;
  }
}

将这种类型的 JSON 映射到这些类的实例中的正确方法是什么?

1 个答案:

答案 0 :(得分:1)

一个选项是遍历节点列表并从每个节点创建一个节点类。在这里,我实现了一个 fromJson 命名构造函数,但存在 dart 包以简化反序列化过程,例如 json_serializable

class Node {
  String id;
  String name;
  String parentId;
  List<Node> nodes;
  
  Node.fromJson(Map<String, dynamic> json) {
    this.id = json["id"];
    this.name = json["name"];
    this.parentId = json["parentId"];
    this.nodes = json["nodes"].map<Node>((node) {
      return Node.fromJson(node);
    }).toList();
  }
}

class Category {
  String id;
  String name;
  List<Node> nodes;
  
  Category.fromJson(Map<String, dynamic> json) {
    this.id = json["id"];
    this.name = json["name"];
    this.nodes = json["nodes"].map<Node>((node) {
      return Node.fromJson(node);
    }).toList();
  }
}

  
final categories = [json list].map<Category>((category) => Category.fromJson(category)).toList();