gpt4 book ai didi

dart - Flutter json 将对象数组映射到类

转载 作者:IT王子 更新时间:2023-10-29 06:54:58 24 4
gpt4 key购买 nike

我想将以下 json 结构映射到模型。我尝试将数组映射到列表,然后将每个集合解析为模型。

将显示以下错误:

类型“MappedListIterable”不是类型“List”的子类型


JSON

  {
"objectId": "vbbZIPV6qs",
"sets": [
{
"repetitions": 10,
"weight": 10,
"time": 0
}
],
"description": "",
"type": "EXERCISE",
}

flutter

class PlanItem {
String type;
String description;
List<Set> sets = [];

PlanItem(this.type, this.description, this.sets);

factory PlanItem.fromJson(Map<String, dynamic> json) {
return PlanItem(
json['type'],
json['description'],
(json['sets'] as List).map((i) {
return Set.fromJson(i);
}).toList(),
);
}
}

class Set {
int repetitions;
int weight;
int time;

Set(this.repetitions, this.weight, this.time);

// convert Json to an exercise object
factory Set.fromJson(Map<String, dynamic> json) {
return Set(
json['repetitions'] as int,
json['weight'] as int,
json['time'] as int,
);
}
}

错误 enter image description here

最佳答案

你的代码完美适合我。

如果我们在下面的代码片段中错过了 toList(),我们将得到这个错误,

(json['sets'] as List).map((i) {
return Set.fromJson(i);
}).toList(), // removing toList will get below error
// type 'MappedListIterable<Map<String, int>, Set>' is not a subtype of type 'List<Set>'

关于dart - Flutter json 将对象数组映射到类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51865016/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com