json - 将带有嵌套映射的 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 映射到这些类的实例中的正确方法是什么?
解决方案
一种选择是遍历节点 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();
推荐阅读
- r - 使用 ggplot 的信息性线性判别图
- reporting-services - SSRS:显示文本而不是数字
- list - 多个半径列表对象的圆区域不可调用
- powershell - Powershell 脚本根据文件的修改日期重命名文件。我对此真的很陌生
- bash - 尝试将 for /f "tokens=*" %%a in ... 转换为 SHELL
- transactions - signrawtransactionwithwallet 显示错误无法签署输入,无效堆栈大小(可能缺少密钥)
- storage - Google Cloud Storage API - StringToSign 返回了错误的存储桶名称
- c# - C#过滤DataGridView - 更新DataTable中的行号
- scala - Scala checkstyle - 忽略特定文件进行检查
- c# - 类没有实现接口成员,因为它没有匹配的返回类型