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())),
    };
}
Share:
114
Miguel Flores
Author by

Miguel Flores

Updated on January 01, 2023

Comments

  • Miguel Flores
    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
      NirmalCode over 2 years
      Please explain the issue, add some code you tried.
  • Miguel Flores
    Miguel Flores over 2 years
    Works perfectly, you saved my life!!! Thanks
  • Akif
    Akif over 2 years
    Ok, now you can accept the answer.