0
votes

Been struggling with JSON deserialization in Flutter.

JSON:

[
  {
    "question": {
      "text": "Some question",
      "url": "Some URL"
    },
    "answer": {
      "text": "Some answer",
      "url": "Some URL"
    },
    "options": [
      {
        "text": "Some option",
        "url": "Some URL"
      },
      {
        "text": "Some option",
        "url": "https://itanium21.github.io/quizGame/option_1.mp3"
      }
    ],
    "fact": {
      "text": "Some fact",
      "url": "Some URL"
    }
  }
]

Code:

class Recording {
  final String text;
  final String url;

  Recording(this.text, this.url);

  factory Recording.fromJson(Map<String, dynamic> json) {
    return Recording(json['text'] as String, json['url'] as String);
  }

  @override
  String toString() {
    return '{ ${this.text}, ${this.url} }';
  }
}

class Question {
  final Recording question;
  final Recording answer;
  final List<Recording> options;
  final Recording fact;

  Question(
      {required this.question,
      required this.answer,
      required this.options,
      required this.fact});

  factory Question.fromJson(Map<String, dynamic> json) {
    var optionObjsJson = json['options'] as List;

    List<Recording> optionObjs = optionObjsJson
        .map((optionJson) => Recording.fromJson(optionJson))
        .toList();

    return Question(
        question: json['question'],
        answer: json['answer'],
        options: optionObjs,
        fact: json['fact']);
  }
}

Error shown in app: type 'IntetnalLinkedHashMap<String, dynamic>' is not a subtype of 'Recording'.

Any ideas? Tried following this tutorial: https://bezkoder.com/dart-flutter-parse-json-string-array-to-object-list/

P.S. I also tried:

List<Recording> optionObjs = optionObjsJson.map((i) => Recording.fromJson(i)).toList();

from https://medium.com/flutter-community/parsing-complex-json-in-flutter-747c46655f51 Unfortunately same result

1
Try generating your model using : app.quicktype.io - Krish Bhanushali

1 Answers

0
votes

Damn! Great resource! Thanks, it helped me! :)