尝试执行此操作时,标题出现错误
我有这种json,其中第一个参数是唯一键
{
"3dfb71719a11693760f91f26f4f79c3c": {
"a": {
"var1": {
"value": "8678468,4,2,2,0,0",
"time": 1544536734000
},
"var2": {
"value": "8678468,4,2,2,0,0",
"time": 1544536734000
},
...
},
"b": {
"var3": {
"value": "8678468,4,2,2,0,0",
"time": 1544536734000
},
...
},
"c": {
"var4": {
"value": "8678468,4,2,2,0,0",
"time": 1544536734000
},
...
}
},
"c91891522a8016fc8a097b9e405b118a": {
"a": {
...
},
"b": {
...
},
"c": {
...
}
}
}
我创建了@JsonSerialiazable()类来处理json
@JsonSeriazable()
class MyResponse {
final List<AType> a;
final List<BType> b;
final List<Ctype> c;
MyResponse(this.a, this.b, this.c);
factory MyResponse.fromJson(Map<String, dynamic> json) => _$MyResponseFromJson(json);
}
class AType {
final StringValueTime var1;
final StringValueTime var2;
...
AType(this.var1, this.var2, ...);
factory AType.fromJson(Map<String, dynamic> json) => $_ATypeFromJson(json);
}
然后,当调用http.get()时,我这样做:
Map<String, dynamic> map = json.decode(response.body);
List<MyResponse> myObjects = List<MyResponse>();
final keys = map.keys;
keys.forEach((id) {
final MyResponse obj = MyResponse.fromJson(map[id]);
myOjects.add(obj);
});
map变量如下所示:
0: "3dfb71719a11693760f91f26f4f79c3c"
key: "3dfb71719a11693760f91f26f4f79c3c"
value: <Map (3 items)>
0: "a" <Map x items>
key: "a"
value: <Map x items>
1: "b" <Map x items>
2: "c" <Map x items>
1: "c91891522a8016fc8a097b9e405b118a"
当调用_ $ MyResponseFromJson(json)时,它会尝试从build_runner生成的my_response.g.dart文件中执行错误(列表为json ['a']作为列表)。
MyResponse _$MyResponseFromJson(Map<String, dynamic> json) {
return MyResponse(
(json['a'] as List)
?.map((e) =>
e == null ? null : AType.fromJson(e as Map<String, dynamic>))
?.toList(),
如何解决该错误?
谢谢
答案 0 :(得分:1)
我在@Irn的帮助下发现了自己的问题。班级应该是这样的
@JsonSeriazable()
class MyResponse {
final AType a;
final BType b;
final Ctype c;
MyResponse(this.a, this.b, this.c);
factory MyResponse.fromJson(Map<String, dynamic> json) => _$MyResponseFromJson(json);
}
class AType {
final StringValueTime var1;
final StringValueTime var2;
...
AType(this.var1, this.var2, ...);
factory AType.fromJson(Map<String, dynamic> json) => $_ATypeFromJson(json);
}
答案 1 :(得分:0)
您的a
,b
和c
字段键入为 lists ,但是JSON在该位置没有列表,只有一个值(作为地图)。
因此,请检查您是否确实希望这些字段为列表,或者它们是否应该只是元素类型的单个值。