您创建 JSON 的方式太复杂了。尝试在每个类上添加 toJson() 方法。如果遇到与 JSON 不兼容的对象,Dart JSON 编码器会自动调用此方法。
这是一个例子:
import 'dart:convert';
class Product {
final String id;
final String desc;
final List<Colors> colors;
Product({
required this.id,
required this.desc,
required this.colors,
});
Map<String, Object> toJson() => {
'id': id,
'desc': desc,
'colors': colors,
};
}
class Colors {
final int id;
final String desc;
final List<Prices> prices;
Colors({
required this.id,
required this.desc,
required this.prices,
});
Map<String, Object> toJson() => {
'id': id,
'desc': desc,
'prices': prices,
};
}
class Prices {
final String id;
final String desc;
final List<Types> types;
Prices({
required this.id,
required this.desc,
required this.types,
});
Map<String, Object> toJson() => {
'id': id,
'desc': desc,
'types': types,
};
}
class Types {
final String id;
final String desc;
final List<Sizes> sizes;
Types({
required this.id,
required this.desc,
required this.sizes,
});
Map<String, Object> toJson() => {
'id': id,
'desc': desc,
'sizes': sizes,
};
}
class Sizes {
final String id;
final int stock;
final String desc;
final bool filled;
int quantity;
final double price;
Sizes({
required this.id,
required this.stock,
required this.desc,
required this.filled,
required this.quantity,
required this.price,
});
Map<String, Object> toJson() => {
'id': id,
'stock': stock,
'desc': desc,
'filled': filled,
'quantity': quantity,
'price': price,
};
}
void main() {
final product = Product(id: '1', desc: 'Some text', colors: [
Colors(id: 1, desc: '', prices: [
Prices(id: '1', desc: '', types: [
Types(id: '1', desc: '', sizes: [
Sizes(
id: '1',
stock: 5,
desc: '',
filled: true,
quantity: 2,
price: 1.0)
])
])
]),
Colors(id: 2, desc: '', prices: [
Prices(id: '1', desc: '', types: [
Types(id: '1', desc: '', sizes: [
Sizes(
id: '5',
stock: 5,
desc: '',
filled: true,
quantity: 2,
price: 1.0),
Sizes(
id: '50',
stock: 5,
desc: '',
filled: true,
quantity: 2,
price: 1.0),
])
])
])
]);
final bag = {
'colors': [
for (final colors in product.colors)
{
'id': colors.id,
'desc': colors.desc,
'sizes': [
for (final prices in colors.prices)
for (final types in prices.types) ...types.sizes
]
}
]
};
print(const JsonEncoder.withIndent(' ').convert(bag));
}
输出:
{
"colors": [
{
"id": 1,
"desc": "",
"sizes": [
{
"id": "1",
"stock": 5,
"desc": "",
"filled": true,
"quantity": 2,
"price": 1.0
}
]
},
{
"id": 2,
"desc": "",
"sizes": [
{
"id": "5",
"stock": 5,
"desc": "",
"filled": true,
"quantity": 2,
"price": 1.0
},
{
"id": "50",
"stock": 5,
"desc": "",
"filled": true,
"quantity": 2,
"price": 1.0
}
]
}
]
}
这里的一个技巧是,Dart 将调用另一个 toJson() 调用返回的结构内的对象。所以例如Product.toJson 返回一个包含颜色列表的 Map<String, Object>。 Dart 然后在每种颜色上调用toJson(),依此类推。