在Dart中为这种形式的Json构建模型



如何解析json的这种形式?在"Question"是对象而不是数组,其中的元素数量不是固定的,而是与"question_ids"的长度有关。其中每个对象的键取自"question_id ">

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

]
}

只需复制并粘贴您的json模型到https://javiercbk.github.io/json_to_dart/,这将自动生成您的模型

如果您希望id在结果中使用

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

如果不需要id,使用

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

你也应该有一个Question类有你需要的所有属性

并使用这一行将数据转换为对象

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

最新更新