后端返回这种json:
已更新:2018-12-27
{
"3dfb71719a11693760f91f26f4f79c3c": {
"a-type": {
"var1": {
"value": "8678468,4,2,2,0,0",
"time": 1544536734000
},
"var2": {
"value": "8678468,4,2,2,0,0",
"time": 1544536734000
}
},
"b-type": {
"var3": {
"value": "8678468,4,2,2,0,0",
"time": 1544536734000
},
},
"c-type": {
"var4": {
"value": "8678468,4,2,2,0,0",
"time": 1544536734000
},
}
},
"c91891522a8016fc8a097b9e405b118a": {
"a-type": {
"var1": {
"value": "8678468,4,2,2,0,0",
"time": 1544536734000
},
"var2": {
"value": "8678468,4,2,2,0,0",
"time": 1544536734000
},
},
"b-type": {
"var3": {
"value": "8678468,4,2,2,0,0",
"time": 1544536734000
},
},
"c-type": {
"var4": {
"value": "8678468,4,2,2,0,0",
"time": 1544536734000
},
}
}
}
第一个参数是唯一键。我想从PoojãBhaumik(https://medium.com/flutter-community/parsing-complex-json-in-flutter-747c46655f51)的一个不错的博客中获得一些启发,但是不确定如何处理上述json。实际上,更多是关于我不知道如何处理它的第一个唯一密钥。
另一件事。我想使用“ flutter packages pub run build_runner build”命令生成.g.dart文件,如解释的here
您介意给我一些提示吗?
谢谢
答案 0 :(得分:1)
如果我清楚理解,您的问题是该地图中的键将是随机的唯一ID。
您可以选择keySet
,然后为每个键循环以创建每个对象以及它自己的嵌套对象。像这样:
void main(){
Map<String, dynamic> map = json.decode('yourBodyResponse');
List<MyObject> myObjects = List<MyObject>();
final keys = map.keys;
keys.forEach((id){
final MyObject obj = MyObject.fromJson(id, map[id]);
myObjects.add(obj);
});
}
class ABC {
final String value;
final int time;
ABC({this.value, this.time});
}
class Def {
final String value;
final int time;
Def({this.value, this.time});
}
class MyObject {
final String id;
final ABC abc;
final Def def;
MyObject({this.id,
this.abc,
this.def
});
factory MyObject.fromJson(String id, Map<String, dynamic> json){
return MyObject(
id: id,
abc: ABC(
value: json['abc']['value'],
time: json['abc']['time']),
def: Def(
value: json['def']['value'],
time: json['def']['time']),
);
}
}
免责声明:我已经使用DartPad在手机上创建了代码,尽管应该可以,但可能格式不正确,缺少括号或有错字。