gpt4 book ai didi

json - 将递归 Json 映射到类 Flutter

转载 作者:行者123 更新时间:2023-12-05 03:37:02 25 4
gpt4 key购买 nike

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com