【问题标题】:How to convert object to json in flutter?如何在颤动中将对象转换为json?
【发布时间】: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: []}}

Screenshot JSON from app

但是来自 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 以便我得到一些提示吗?

标签: json object flutter dart


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-09-30
    • 1970-01-01
    • 2021-05-01
    • 2019-08-13
    • 1970-01-01
    • 2021-04-20
    • 2020-11-25
    • 2022-01-08
    相关资源
    最近更新 更多