首页 > 解决方案 > 将带有嵌套映射的 JSON 映射到对象

问题描述

我有一个由类别组成的 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 映射到这些类的实例中的正确方法是什么?

标签: jsonfluttermapping

解决方案


一种选择是遍历节点 List 并从每个节点创建一个 Node 类。在这里,我实现了一个 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();


推荐阅读