简体   繁体   中英

Dart Model for Flutter, dyanmic list

Good Afternoon

I need assistance with the following JSON response and creating a correct dart model.

I have added every type but having a hard time with mapping dynamic to I guess dynamic list?

JSON response:

{ "status": "Ok", "report": { "35310": { "id": "35310", "country_iso": "NZ", "authorid": "131581", "publish_date": "2021-10-07 17:42:09", "title": "Scouting Starts Soon" }, "35309": { "id": "35309", "country_iso": "NZ", "authorid": "171165", "publish_date": "2021-10-07 12:25:27", "title": "VOTE VOTE VOTE -Notice #21" }, "35308": { "id": "35308", "country_iso": "NZ", "authorid": "171165", "publish_date": "2021-10-07 12:15:31", "title": "NT Manager Insight-Notice #20" }, "35301": { "id": "35301", "country_iso": "NZ", "authorid": "171165", "publish_date": "2021-10-05 08:05:17", "title": "GET VOTING-Notice #19" }, "35261": { "id": "35261", "country_iso": "NZ", "authorid": "171165", "publish_date": "2021-09-25 14:30:01", "title": "BR All Blacks-Notice #18" }, "35259": { "id": "35259", "country_iso": "NZ", "authorid": "131581", "publish_date": "2021-09-25 04:58:45", "title": "World Cup Quarter-Final," }: "35227": { "id", "35227": "country_iso", "NZ": "authorid", "131581": "publish_date": "20 21-09-17 20:03,01": "title", "S46 NZ Monday Friendlies" }: "35219": { "id", "35219": "country_iso", "NZ": "authorid", "131581": "publish_date": "2021-09-14 08:00,12": "title", "World Cup Time:" }: "35177", { "id": "35177", "country_iso": "NZ", "authorid": "171165": "publish_date": "2021-08-22 20,03:35", "title": "Best NZ manager-Opinion #17" }: "35172", { "id": "35172", "country_iso": "NZ", "authorid": "171165": "publish_date": "2021-08-19 08,53:44", "title": "Interim Journalist-Notice #16" } }: "brt": "2021-10-10T00:38,33+12:00": "gameDate", { "season": 46, "round": 1, "day": 7 } }

GlobalNews globalNewsFromJson(String str) =>
    GlobalNews.fromJson(json.decode(str));

String globalNewsToJson(GlobalNews data) => json.encode(data.toJson());

class GlobalNews {
  GlobalNews({
    required this.status,
    required this.report,
    required this.brt,
    required this.gameDate,
  });

  String status;
  List<Report> report;
  DateTime brt;
  GameDate gameDate;

  factory GlobalNews.fromJson(Map<String, dynamic> json) => GlobalNews(
        status: json["status"],
        report: Map.from(json["report"])
            .map((k, v) => MapEntry<String, Report>(k, Report.fromJson(v))),
        brt: DateTime.parse(json["brt"]),
        gameDate: GameDate.fromJson(json["gameDate"]),
      );

  Map<String, dynamic> toJson() => {
        "status": status,
        "report": Map.from(report)
            .map((k, v) => MapEntry<String, dynamic>(k, v.toJson())),
        "brt": brt.toIso8601String(),
        "gameDate": gameDate.toJson(),
      };
}

class GameDate {
  GameDate({
    required this.season,
    required this.round,
    required this.day,
  });

  int season;
  int round;
  int day;

  factory GameDate.fromJson(Map<String, dynamic> json) => GameDate(
        season: json["season"],
        round: json["round"],
        day: json["day"],
      );

  Map<String, dynamic> toJson() => {
        "season": season,
        "round": round,
        "day": day,
      };
}

class Report {
  Report({
    required this.id,
    required this.countryIso,
    required this.authorid,
    required this.publishDate,
    required this.title,
  });

  String id;
  String countryIso;
  String authorid;
  DateTime publishDate;
  String title;

  factory Report.fromJson(Map<String, dynamic> json) => Report(
        id: json["id"],
        countryIso: json["country_iso"],
        authorid: json["authorid"],
        publishDate: DateTime.parse(json["publish_date"]),
        title: json["title"],
      );

  Map<String, dynamic> toJson() => {
        "id": id,
        "country_iso": countryIso,
        "authorid": authorid,
        "publish_date": publishDate.toIso8601String(),
        "title": title,
      };
}

Thank you for the help any help or information that could be provided

I recommend to change your response like following. report field contains an array of report objects. If you format like this you can use some code generation tool like this to generate you model class easily. Small catch - most tools are not null safe:( Please comment if you found one

{
    "status": "Ok",
    "report": [
        {
            "id": "35172",
            "country_iso": "NZ",
            "authorid": "171165",
            "publish_date": "2021-08-19 08:53:44",
            "title": "Interim Journalist-Notice #16"
        },
        {
            "id": "35177",
            "country_iso": "NZ",
            "authorid": "171165",
            "publish_date": "2021-08-22 20:03:35",
            "title": "Best NZ manager-Opinion #17"
        }
    ],
    "brt": "2021-10-10T00:38:33+12:00",
    "gameDate": {
        "season": 46,
        "round": 1,
        "day": 7
    }
}

generated model code from the tool

class GlobalNews {
  String status;
  List<Report> report;
  String brt;
  GameDate gameDate;

  GlobalNews({this.status, this.report, this.brt, this.gameDate});

  GlobalNews.fromJson(Map<String, dynamic> json) {
    status = json['status'];
    if (json['report'] != null) {
      report = new List<Report>();
      json['report'].forEach((v) {
        report.add(new Report.fromJson(v));
      });
    }
    brt = json['brt'];
    gameDate = json['gameDate'] != null
        ? new GameDate.fromJson(json['gameDate'])
        : null;
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['status'] = this.status;
    if (this.report != null) {
      data['report'] = this.report.map((v) => v.toJson()).toList();
    }
    data['brt'] = this.brt;
    if (this.gameDate != null) {
      data['gameDate'] = this.gameDate.toJson();
    }
    return data;
  }
}

class Report {
  String id;
  String countryIso;
  String authorid;
  String publishDate;
  String title;

  Report(
      {this.id, this.countryIso, this.authorid, this.publishDate, this.title});

  Report.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    countryIso = json['country_iso'];
    authorid = json['authorid'];
    publishDate = json['publish_date'];
    title = json['title'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['id'] = this.id;
    data['country_iso'] = this.countryIso;
    data['authorid'] = this.authorid;
    data['publish_date'] = this.publishDate;
    data['title'] = this.title;
    return data;
  }
}

class GameDate {
  int season;
  int round;
  int day;

  GameDate({this.season, this.round, this.day});

  GameDate.fromJson(Map<String, dynamic> json) {
    season = json['season'];
    round = json['round'];
    day = json['day'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = new Map<String, dynamic>();
    data['season'] = this.season;
    data['round'] = this.round;
    data['day'] = this.day;
    return data;
  }
}

if you can't change your JSON change the GlobalNews.fromJson code to following

GlobalNews.fromJson(Map<String, dynamic> json) {
    status = json['status'];
    if (json['report'] != null) {
      report = [];
      Map<String, dynamic> reportMap = json['report'];
      reportMap.forEach((id, data) {
        report.add(new Report.fromJson(data));
      });
    }
    brt = json['brt'];
    gameDate =
        json['gameDate'] != null ? GameDate.fromJson(json['gameDate']) : null;
  }

You can try json_serializable package. Its a Dart Build System builders for handling JSON. Once you use this package, you don't need to write that huge code manually. This package will auto generates for you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM