【问题标题】:Map recursive Json to Class Flutter将递归 Json 映射到 Flutter 类
【发布时间】:2021-11-26 21:16:12
【问题描述】:

我需要将此 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;
}

【问题讨论】:

  • 请解释问题,添加一些您尝试过的代码。

标签: json flutter recursion


【解决方案1】:

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

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

【讨论】:

  • 完美运行,你救了我的命!!!谢谢
  • 好的,现在你可以接受答案了。
猜你喜欢
  • 2015-10-02
  • 1970-01-01
  • 2020-05-20
  • 2016-10-22
  • 2015-12-27
  • 2017-12-24
  • 2022-08-11
  • 2021-04-23
  • 1970-01-01
相关资源
最近更新 更多