首页 > 解决方案 > 如何在颤动中将对象转换为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: []}}

来自应用程序的屏幕截图 JSON

但是来自 DartPad 的 JSON 是

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

DartPad 控制台的屏幕截图 JSON

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

标签: jsonobjectflutterdart

解决方案


而不是像示例中那样直接调用.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":[]}

推荐阅读