json - 如何在颤动中将对象转换为json?
问题描述
我想将我的对象转换为 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":[]}
如何在我的应用程序上获得相同的输出。请帮忙。另外为什么 DartPad 和应用程序不相似?
解决方案
而不是像示例中那样直接调用.toJson()
使用jsonEncode()(您可以在 DartPad 中运行它以查看差异)。调用jsonEncode(order)
将为您提供格式正确的 json。
import 'dart:convert';
void main() {
final obj = Order();
print(obj.toJson());
print(jsonEncode(obj));
}
class Order {
int id = 0;
int price = 100;
String name = 'asdf';
int quantity = 10;
Map<String, dynamic> toJson() => {
"id": id.toString(),
"name": name,
"price": price,
"quantity": quantity.toString(),
"attributes": {},
"conditions": []
};
}
输出:
// simple toJson that ommits quotation marks
{id: 0, name: asdf, price: 100, quantity: 10, attributes: {}, conditions: []}
// properly encoded json
{"id":"0","name":"asdf","price":100,"quantity":"10","attributes":{},"conditions":[]}
推荐阅读
- git - git 重新提交对 subbranch-a 所做的更改到 subbranch-b
- c# - 如果文档太长,PDF 文件会损坏 - itextsharp
- django - Django apache内部服务器错误
- liferay - Liferay:如何使用 groupID 获取友好的 URL 列表
- python - 如何使用 Quart Python 停止将访问日志记录到标准输出
- java - 如何在 Eclipse 中运行 JUnit 5 测试
- android - Webview 到 Coordinator 布局
- regex - 将系统资源动态映射到 apache 中请求的 uri
- angular - 如何在角度 ngfor 中显示来自 Firebase 存储的文件
- audio - 使用 VLC over http 流式传输 MP4 视频没有音频