无法解析颤振中的json数据

时间:2021-05-15 18:39:56

标签: json flutter

我无法在 flutter 中解析下面提到的 json 数据。

[ { “身份证”:96, "name": "娱乐", "link": "https://thehappilyeverafter.in/listing-category/entertainment/", "图片": "https://thehappilyeverafter.in/wp-content/uploads/2021/05/a685b39b20592b03c0939878edb0cb84.jpg", “孩子们”: [ { “child_id”:114, "child_name": "DJ", "child_link": "https://thehappilyeverafter.in/listing-category/djs/" }, { “child_id”:117, "child_name": "现场音乐", "child_link": "https://thehappilyeverafter.in/listing-category/live-music/" }, { “child_id”:115, "child_name": "婚礼编舞", "child_link": "https://thehappilyeverafter.in/listing-category/wedding-choreographer/" }, { “child_id”:116, "child_name": "婚礼娱乐", "child_link": "https://thehappilyeverafter.in/listing-category/wedding-entertainment/" } ] }

]`

import 'dart:convert';

List<Root> rootFromJson(String str) => List<Root>.from(json.decode(str).map((x) => Root.fromJson(x)));

String rootToJson(List<Root> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));


class Root {
  Root({
    this.id,
    this.name,
    this.link,
    this.image,
    this.children,
  });

  int id;
  String name;
  String link;
  String image;
  List<Children> children;

  factory Root.fromJson(Map<String, dynamic> json) => Root(
    id: json["id"],
    name: json["name"],
    link: json["link"],
    image: json["image"] == null ? null : json["image"],
    children: List<Children>.from(json["children"].map((x) => Children.fromJson(x))),
  );

  Map<String, dynamic> toJson() => {
    "id": id,
    "name": name,
    "link": link,
    "image": image == null ? null : image,
    "children": List<dynamic>.from(children.map((x) => x.toJson())),
  };
}

class Children {
  Children({
    this.childId,
    this.childName,
    this.childLink,
  });

  int childId;
  String childName;
  String childLink;

  factory Children.fromJson(Map<String, dynamic> json) => Children(
    childId: json["child_id"],
    childName: json["child_name"],
    childLink: json["child_link"],
  );

  Map<String, dynamic> toJson() => {
    "child_id": childId,
    "child_name": childName,
    "child_link": childLink,
  };
}

[得到这个错误][1] ` “List”类型不是“Children”类型的子类型

1 个答案:

答案 0 :(得分:0)

由于你的 json 是一个列表,你应该遍历它:

final List<Root> roots = yourJson.map((element) {
  return Root.fromJson(element);
}).toList();

print(roots.first.image);
//https://thehappilyeverafter.in/wp-content/uploads/2021/05/a685b39b20592b03c0939878edb0cb84.jpg