json - 将递归 Json 映射到类 Flutter

标签 json flutter recursion

我需要将此 Json 映射到递归类,有什么想法吗?

[
{
"title": "home",
"icono": "assets/iconos/home.png",
"children": [
  {
    "title": "sub home 1",
    "icono": "assets/iconos/home.png",
    "children": [
      {
        "title": "sub home 2",
        "icono": "assets/iconos/home.png",
        "children": []
      }
    ]
  }
 ]
},
{
"title": "home",
"icono": "assets/iconos/home.png",
"children": []
}
]

class Entry {
  Entry(this.title,this.icono,[this.children = const <Entry>[]]);
  final String title;
  final String icono;
  final List<Entry> children;
}

最佳答案

您可以使用 this website从 JSON 创建任何 dart 类。您的递归模型应如下所示:

// To parse this JSON data, do
//
//     final entry = entryFromJson(jsonString);

import 'dart:convert';

List<Entry> entryFromJson(String str) => List<Entry>.from(json.decode(str).map((x) => Entry.fromJson(x)));

String entryToJson(List<Entry> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

class Entry {
    Entry({
        this.title,
        this.icono,
        this.children,
    });

    String title;
    String icono;
    List<Entry> children;

    factory Entry.fromJson(Map<String, dynamic> json) => Entry(
        title: json["title"] == null ? null : json["title"],
        icono: json["icono"] == null ? null : json["icono"],
        children: json["children"] == null ? null : List<Entry>.from(json["children"].map((x) => Entry.fromJson(x))),
    );

    Map<String, dynamic> toJson() => {
        "title": title == null ? null : title,
        "icono": icono == null ? null : icono,
        "children": children == null ? null : List<dynamic>.from(children.map((x) => x.toJson())),
    };
}

关于json - 将递归 Json 映射到类 Flutter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69469993/

相关文章:

android - 如何使用 Retrofit/Kotlin 仅提取一个对象或 Json 文件数组?

flutter - 如何检查给定的路径是图像还是视频?

recursion - 条件和递归

javascript - jsrender-从复杂结构中访问元素

java - 在 Java 中解析格式错误的 json

flutter 从对象中获取值并显示在 Text() 中

google-maps - Flutter Google Maps 无法确定设备的当前位置

recursion - 这个 lisp 示例是否以尾递归为特色?

mysql - 在非递归过程中超出递归限制

php - 如何从 PHP 中的 MySQL 准备语句生成 JSON?