Map recursive Json to Class Flutter
114
You can use this website to create any dart class from JSON. Your recursive model should look like this:
// 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())),
};
}
Author by
Miguel Flores
Updated on January 01, 2023Comments
-
Miguel Flores over 1 year
I need to map this Json to recursive class, any idea?
[ { "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; }
-
NirmalCode over 2 yearsPlease explain the issue, add some code you tried.
-
-
Miguel Flores over 2 yearsWorks perfectly, you saved my life!!! Thanks
-
Akif over 2 yearsOk, now you can accept the answer.