首页 > 解决方案 > 从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"
    }
  ]
}

谢谢你。

标签: arraysloopsflutterdartmultidimensional-array

解决方案


模型类

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(),
    );
  }
}

推荐阅读