簡體   English   中英

使用嵌套映射將 JSON 映射到對象

[英]Mapping JSON with nested maps to objects

我有一個包含類別的 JSON 結構。 這些類別可以有不同數量的節點,並且這些節點內部也有一個 map 節點。 此 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;
  }
}

將這種類型的 map 和 JSON 放入這些類的實例中的正確方法是什么?

一種選擇是遍歷節點列表並從每個節點創建一個節點 class。 在這里,我實現了一個 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();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM