简体   繁体   English

用嵌套的列表对象解析 JSON 到 Dart

[英]Parse JSON to Dart with nested List objects

How to parse from JSON to Dart object including 2 nested classes inside of properties oof the class, Lists ?如何从 JSON 解析到 Dart object,包括 class Lists属性中的 2 个嵌套类?

A JSON object Video that contains a list of Question objects.包含Question对象列表的 JSON object Video

Question objects contains a list of Ans objects. Question对象包含Ans对象的列表。

    {
      "id": 1,
      "videoUrl": "https://assets.mixkit.co/videos/preview/mixkit-machinery-of-a-very-close-watch-3673-large.mp4",
      "questions": [
        {
          "id": "0-903669-72-2",
          "type": "mc",
          "body": "Understand reality truth food agency artist.",
          "correctAnswerId": "0-259-85157-4",
          "ans": [
            {
              "id": "0-259-85157-4",
              "body": "Play."
            },
            {
              "id": "0-694-71578-6",
              "body": "Whose trip."
            },
            {
              "id": "0-13-124278-4",
              "body": "Of figure why."
            },
            {
              "id": "0-8169-6726-1",
              "body": "Station culture green."
            }
          ]
        },
        {
          "id": "1-872297-31-5",
          "type": "mc",
          "body": "Especially resource benefit beautiful world six.",
          "correctAnswerId": "1-61799-113-9",
          "ans": [
            {
              "id": "0-384-69655-4",
              "body": "Form."
            },
            {
              "id": "0-89336-975-6",
              "body": "Call."
            },
            {
              "id": "1-61799-113-9",
              "body": "Money three young."
            },
            {
              "id": "1-60950-585-9",
              "body": "Three threat back."
            }
          ]
        },
        {
          "id": "0-297-13339-X",
          "type": "mc",
          "body": "Of smile coach second firm ahead.",
          "correctAnswerId": "1-916803-19-9",
          "ans": [
            {
              "id": "0-15-955520-5",
              "body": "Add old catch."
            },
            {
              "id": "0-606-65499-2",
              "body": "Well great task."
            },
            {
              "id": "0-7364-1942-X",
              "body": "Arrive resource speech kid."
            },
            {
              "id": "1-916803-19-9",
              "body": "Reach brother book."
            }
          ]
        },
        {
          "id": "0-254-52906-2",
          "type": "ms",
          "correctAnswers": [
            "1-146-90255-7",
            "0-17-470673-1"
          ],
          "body": "Particularly affect but necessary.",
          "ans": [
            {
              "id": "0-17-278557-X",
              "body": "Response bill."
            },
            {
              "id": "0-17-470673-1",
              "body": "Attack sister interview."
            },
            {
              "id": "0-16-027096-0",
              "body": "Design garden."
            },
            {
              "id": "1-146-90255-7",
              "body": "Short break."
            }
          ]
        },
        {
          "id": "0-926285-49-1",
          "type": "ms",
          "correctAnswers": [
            "0-554-50421-9",
            "0-294-02768-8"
          ],
          "body": "Experience family training.",
          "ans": [
            {
              "id": "0-8260-5153-7",
              "body": "Mouth exist kid."
            },
            {
              "id": "0-294-02768-8",
              "body": "Agreement factor."
            },
            {
              "id": "0-554-50421-9",
              "body": "Down race professional show."
            },
            {
              "id": "1-124-45547-7",
              "body": "Most such onto strategy."
            }
          ]
        }
      ]
    }

I tried using this tool after failing to properly do this myself.在我自己未能正确执行此操作后,我尝试使用此工具。 https://javiercbk.github.io/json_to_dart/ https://javiercbk.github.io/json_to_dart/

This is the class definitions I got(I changed some things because of VSCode suggestions).这是我得到的 class 定义(我根据 VSCode 建议更改了一些内容)。

class Video {
  int? id;
  String? videoUrl;
  List<Question>? questions;

  Video({this.id, this.videoUrl, this.questions});

  Video.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    videoUrl = json['videoUrl'];
    if (json['questions'] != null) {
      questions = <Question>[];
      json['questions'].forEach((v) {
        questions!.add(Question.fromJson(v));
      });
    }
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['id'] = id;
    data['videoUrl'] = videoUrl;
    if (this.questions != null) {
      data['questions'] = questions!.map((v) => v.toJson()).toList();
    }
    return data;
  }
}

class Question {
  String? id;
  String? type;
  String? body;
  String? correctAnswerId;
  List<Ans>? ans;
  List<String>? correctAnswers;

  Question(
      {this.id,
      this.type,
      this.body,
      this.correctAnswerId,
      this.ans,
      this.correctAnswers});

  Question.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    type = json['type'];
    body = json['body'];
    correctAnswerId = json['correctAnswerId'];
    if (json['ans'] != null) {
      ans = <Ans>[];
      json['ans'].forEach((v) {
        ans!.add(Ans.fromJson(v));
      });
    }
    correctAnswers = json['correctAnswers'].cast<String>();
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['id'] = id;
    data['type'] = type;
    data['body'] = body;
    data['correctAnswerId'] = correctAnswerId;
    if (ans != null) {
      data['ans'] = ans!.map((v) => v.toJson()).toList();
    }
    data['correctAnswers'] = correctAnswers;
    return data;
  }
}

class Ans {
  String? id;
  String? body;

  Ans({this.id, this.body});

  Ans.fromJson(Map<String, dynamic> json) {
    id = json['id'];
    body = json['body'];
  }

  Map<String, dynamic> toJson() {
    final Map<String, dynamic> data = <String, dynamic>{};
    data['id'] = id;
    data['body'] = body;
    return data;
  }
}

I load the JSON like this.我像这样加载 JSON。

getVid() async {
    final String response = await rootBundle.loadString('assets/videos.json');
    final data = await json.decode(response)['videos'];
    List<Video> vids = List<Video>.from(data.map((x) => Video.fromJson(x)));
}

But end up with this error message inside of the console.但最终会在控制台中出现此错误消息。

Uncaught (in promise) Error: NoSuchMethodError: 'cast'
Dynamic call of null.
Receiver: null
Arguments: []

Your help is greatly appreciated!非常感谢您的帮助!

This line of code correctAnswers = json['correctAnswers'].cast<String>();这行代码correctAnswers = json['correctAnswers'].cast<String>(); is causing error, as it is not able to cast it as list of string导致错误,因为它无法将其转换为字符串列表

Try using List.from() or map() or List.of() methods尝试使用List.from()map()List.of()方法

correctAnswers = List<String>.from(json['correctAnswers']);

Or或者

correctAnswers = json['correctAnswers'].map((answer) => answer.toString()).toList();

Or或者

correctAnswers = List<String>.of(json['correctAnswers']);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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