如何在Flutter中将对象转换为JSON?

3
我想将我的对象转换为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: []}}

应用截图中的JSON

但是在DartPad上的JSON则为:

{"id":"1","name":"Sabin","price":200,"quantity":3,"attributes":{},"conditions":[]}

从DartPad控制台截取的JSON屏幕截图

我该如何在我的应用程序上获得相同的输出,请帮忙。另外为什么DartPad和应用程序的输出不相似?


你可以在模型类中创建一个fromJson方法,该方法返回工厂构造函数。 - Abhishek Ghaskata
@AbhishekGhaskata 如果我说错了,请纠正我... fromJson 只是将 JSON 转换为对象,对吗?我只需要将对象转换为 JSON。 - coder0
是的,你说得对,我认为你需要进行类型转换。 - Abhishek Ghaskata
@AbhishekGhaskata,你能分享一些代码片段吗?这样我就可以得到一些提示了吗? - coder0
1个回答

6

不要直接调用.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":[]}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接