arrays - 从JSON中循环未知深度多维数组
问题描述
我有一个数组,这个数组是从 JSON 中得到的,但是这个数组不知道有多深,我只想让它成为 2 维的父母和孩子。我只制作了 3 个维度的示例,但在实际情况下它可能是未知的。
该数组具有来自父级和子级的相同对象。您可以在此处查看示例。
由此 :
{
"brand_id": "1",
"name": "Civic",
"type": "Sedan",
"children": [
{
"brand_id": "1",
"name": "Civic Type-R",
"type": "Sedan",
"children": [
{
"brand_id": "1",
"name": "Civic Type-R 2020",
"type": "Sedan",
"children": [
{
"brand_id": "1",
"name": "Civic Type-R 2020 A",
"type": "Sedan"
},
{
"brand_id": "1",
"name": "Civic Type-R 2020 B",
"type": "Sedan"
}
]
},
{
"brand_id": "1",
"name": "Civic Type-R 2019",
"type": "Sedan",
"children": [
{
"brand_id": "1",
"name": "Civic Type-R 2019 A",
"type": "Sedan"
}
]
}
]
}
]
}
我希望从示例中可以是这样的:
{
"brand_id": "1",
"name": "Civic",
"type": "Sedan",
"children": [
{
"brand_id": "1",
"name": "Civic Type-R",
"type": "Sedan"
},
{
"brand_id": "1",
"name": "Civic Type-R 2020",
"type": "Sedan"
},
{
"brand_id": "1",
"name": "Civic Type-R 2020 A",
"type": "Sedan"
},
{
"brand_id": "1",
"name": "Civic Type-R 2020 B",
"type": "Sedan"
},
{
"brand_id": "1",
"name": "Civic Type-R 2019",
"type": "Sedan"
},
{
"brand_id": "1",
"name": "Civic Type-R 2019 A",
"type": "Sedan"
}
]
}
谢谢你。
解决方案
模型类
import 'dart:convert';
class MyModel {
String brand_id;
String name;
String type;
List<ChildrenModel> children;
MyModel({
this.brand_id,
this.name,
this.type,
this.children,
});
factory MyModel.fromJson(Map<String, dynamic> json) {
return new MyModel(
brand_id: json['brand_id'].toString(),
name: json['name'].toString(),
type: json['type'].toString(),
children: (json['children'] as List).map((i) => ChildrenModel.fromJson(i)).toList(),
);
}
}
class ChildrenModel {
String brand_id;
String name;
String type;
ChildrenModel({
this.brand_id,
this.name,
this.type,
});
factory ChildrenModel.fromJson(Map<String, dynamic> json) {
return new ChildrenModel(
brand_id: json['brand_id'].toString(),
name: json['name'].toString(),
type: json['type'].toString(),
);
}
}
推荐阅读
- java - net.sf.jasperreports.engine.JRException:java.net.MalformedURLException:无法调用“String.length()”,因为“spec”为空
- kotlin - Kotlin 反射获取参数作为字符串
- .net - InitializeComponent() 不存在 - 多目标项目 (4.6.1 & 5)
- teradata - 通过 .NET 连接器查询的错误结果,但直接在 Teradata Studio 中更正了结果
- sql - 每个点返回的行数 PostGIS
- javascript - Nodemailer连接错误仅在服务器上
- r - ggplot2如何仅对数据的某些行着色
- java - 将jOOQ表达式分配给局部变量时如何防止Eclipse添加@NotNull注释
- python - 在 python 套接字服务器上从客户端接收文件
- tarantool - 如何在 tarantool 中将乙烯基转换为 memtx?