让我们假设,直到最近,我还是在吼叫Json response
{
"AA": {
"product": {
"id":"111",
"type":"C"
}
}
}
而且,我写了下面的波纹管model.dart
,将其从json转换为对象
model.dart
@JsonSerializable()
class ResponseGate {
@JsonKey(name: "AA")
AA aa;
ResponseGate({this.aa});
factory ResponseGate.fromJson(Map<String, dynamic> json) =>
_$ResponseGateFromJson(json);
}
@JsonSerializable()
class AA {
@JsonKey(name: "product")
Product product;
AA(this.product);
factory AA.fromJson(Map<String, dynamic> json) => _$AAFromJson(json);
}
@JsonSerializable()
class Product {
@JsonKey(name: "id")
var id;
@JsonKey(name: "type")
var type;
Product(this.id, this.type);
factory Product.fromJson(Map<String, dynamic> json) =>
_$ProductFromJson(json);
}
然后,响应变得像下面这样。仅添加了另一个对象。
{
"AA": {
"product": {
"id":"111",
"type":"C"
}
},
"BB": {
"product": {
"id":"222",
"type":"d"
}
}
}
键(AA和BB)不同,但它们的子键相同。为了使我的代码能够识别所有键并使用model.dart
从json转换为模型,我该怎么做?
if (thirdResponse.statusCode == 200) {
var map = json.decode(thirdResponse.body) as Map<String, dynamic>;
ResponseGate responseGate = new ResponseGate.fromJson(map);
else {
throw Exception('Failed to load post: ${thirdResponse.statusCode}');
}
答案 0 :(得分:1)
我看到您已经解码了地图,所以这是我在dartpad中测试过的代码。
Map
, var data ={
"AA": {
"product": {
"id":"111",
"type":"C"
}
},
"BB": {
"product": {
"id":"222",
"type":"d"
}
}
};
var list = new List();
data.forEach((key, value){
list.add(value);
});
print(list);
Product
for(var productInfo in list)
{
Product product = new Product.fromJson(productInfo);
// add product to your List...
}
或者您可以将两者结合在一起,也可以获取密钥。
data.forEach((key, value){
Product product = new Product.fromJson(value);
// add product to your List...
// or make a Map to store (key, product)
});
但是还有另一种方法,将api修改为数组,并在json响应上更有意义。
[
{
"productName": "AA"
"id":"222",
"type":"d"
}
]
开个玩笑,说说最后的方法吧,因为您没有过多谈论自己的情况。
答案 1 :(得分:-2)
请勿使用模型尝试将您的回复放入地图中 然后例如
{
"AA": {
"product": {
"id":"111",
"type":"C"
}
},
"BB": {
"product": {
"id":"222",
"type":"d"
}
}
}
如果要“ BB”“产品”“ id” 会这样
map['BB']['product']['id']