假設我有這樣的資料結構
@JsonSerializable(explicitToJson: true)
class CartItem {
final Product product;
...
}
@JsonSerializable()
class Product {
final String id;
...
}
@JsonSerializable()
class Food extends Product {
final String foodName;
...
}
@JsonSerializable()
class Furniture extends Product {
final String furnitureName;
...
}
我想要的是當我使用CartItem.toJson()
它匯出到 Json 映射時對應的是什么型別Product
。
例如
var x = CartItem(
product: Food(
id: '1100112',
foodName: 'Hamburger',
),
)
print(x.toJson());
這應該導致
{
'product': {
'id': '1100112',
'foodName': 'Hamburger',
}
}
使用時fromJson
,產品也會有型別Food
x.fromJson(x.toJson()) as Food //This should not error
uj5u.com熱心網友回復:
我假設您正在使用 package json_serialization
。對于每個類,您都需要定義以下一些方法:
例如:
factory CartItem.fromJson(Map<String, dynamic> json) => _$CartItemFromJson(json);
Map<String, dynamic> toJson() => _$CartItemToJson(this);
然后您將運行生成命令列:
flutter pub run build_runner build
這將自動生成.g.dart
與您的模型檔案對應的檔案。
參考:https ://pub.dev/packages/json_serializable
否則,如果您希望手動定義方法:
class CartItem {
final Product product;
CartItem({required this.product});
/// fromJson
factory CartItem.fromJson(Map<String, dynamic> json) => CartItem(
product: Product.fromJson(json["product"])
);
/// toJson
Map<String, dynamic> toJson() => {
"product": product.toJson()
};
}
class Product {
final String id;
Product({required this.id});
/// fromJson
factory Product.fromJson(Map<String, dynamic> json) => Product(
id: json["id"]
);
/// toJson
Map<String, dynamic> toJson() => {
"id": id
};
}
class Food extends Product {
final String foodName;
Food({required String id, required this.foodName}) : super(id: id);
/// fromJson
factory Food.fromJson(Map<String, dynamic> json) => Food(
id: json["id"],
foodName: json["foodName"]
);
/// toJson
@override
Map<String, dynamic> toJson() => {
"id": id,
"foodName": foodName
};
}
class Furniture extends Product {
final String furnitureName;
Furniture({required String id, required this.furnitureName}) : super(id: id);
/// fromJson
factory Furniture.fromJson(Map<String, dynamic> json) => Furniture(
id: json["id"],
furnitureName: json["furnitureName"]
);
/// toJson
@override
Map<String, dynamic> toJson() => {
"id": id,
"furnitureName": furnitureName
};
}
定義后,您可以執行以下操作:
var x = CartItem(
product: Food(
id: '1100112',
foodName: 'Hamburger',
),
)
print(x.toJson());
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/480545.html
下一篇:返回列表