Home > Blockchain >  Map recursive Json to Class Flutter
Map recursive Json to Class Flutter

Time:10-07

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;
}

CodePudding user response:

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