【发布时间】:2020-08-11 22:36:13
【问题描述】:
我想将我的对象转换为 JSON,所以我实现了以下代码
import "package:behoove/models/product.dart";
class Order {
Product _product;
int _quantity;
int _id;
Order(this._product, this._quantity, this._id);
int get id => _id;
int get quantity => _quantity;
Product get product => _product;
double get orderPrice => _quantity * double.parse(_product.discountedPrice ?? _product.price);
Map<String, dynamic> toJson() => {
"id": _product.id.toString(),
"name": _product.name,
"price": _product.price,
"quantity": _quantity.toString(),
"attributes": {},
"conditions": []
};
}
来自应用程序的 JSON 是
{id: 9, name: GoldStar Classic 032, price: 1200, quantity: 1, attributes: {}, conditions: []}}
但是来自 DartPad 的 JSON 是
{"id":"1","name":"Sabin","price":200,"quantity":3,"attributes":{},"conditions":[]}
Screenshot JSON from DartPad console
如何在我的应用上获得相同的输出。请帮忙。另外为什么 DartPad 和应用程序不相似?
【问题讨论】:
-
可以在模型类中创建fromJson方法,返回工厂构造函数
-
@AbhishekGhaskata 如果我错了,请纠正我... fromJson 只是将 json 转换为对象,对吗?我只需要将对象转换为 JSON。
-
是的,你是对的,我认为你需要类型转换
-
@AbhishekGhaskata 你能分享一些代码 sn-p 以便我得到一些提示吗?