Mahmoud Abu salou
Mahmoud Abu salou

Reputation: 1

Build Model In Dart For This Form Of Json

how I can parse this form of json ? Where "Question" is an object and not an array, the number of elements within it is not fixed but is related to the length of "question_ids" and the key of each object within it is taken from "question_ids"

{
"questions": {
                "96292": {
                    "correct": false,
                    "mark": 0,
                    "answered": ""
                },
                "96293": {
                    "correct": false,
                    "mark": 0,
                    "answered": ""
                },
                "96294": {
                    "correct": false,
                    "mark": 0,
                    "answered": ""
                }
            },
"question_ids": [
            96292,
            96293,
            96294
           
        ]
}

Upvotes: 0

Views: 178

Answers (2)

anggadaz
anggadaz

Reputation: 390

just copy and paste your json model to https://javiercbk.github.io/json_to_dart/ this will auto generate your model

Upvotes: 1

Ali Ammar
Ali Ammar

Reputation: 384

if you want the id to be in the result use

  final jsonMap = jsonDecode(valueFromApi);
  final questions = (jsonMap['questions'] as Map<String, Map>?)
      ?.entries
      .map<Map>((item) => {"id": item.key, ...item.value});

if you don't need the id use

  final jsonMap = jsonDecode(valueFromApi);
  final questions = (jsonMap['questions'] as Map<String, Map>?)
      ?.entries
      .map<Map>((item) => item.value);

you should also have a Question class has all the attribute you need

and use this line to convert your data to object

 final entity = questions?.map((e) => Question.fromJson(e)).toList();

Upvotes: 0

Related Questions