簡體   English   中英

如何在 flutter 中將 object 轉換為 json?

[英]How to convert object to json in flutter?

我想將我的 object 轉換為 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

如何在我的應用程序上獲得相同的 output。 請幫忙。 另外為什么 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": []
      };
}

Output:

// 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":[]}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM