How to convert object to json in flutter?

2,812

Instead of calling .toJson() directly use jsonEncode() as in the example (you can run it in DartPad to see difference). Calling jsonEncode(order) will give you a properly formatted 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":[]}
Share:
2,812
Admin
Author by

Admin

Updated on December 19, 2022

Comments

  • Admin
    Admin over 1 year

    I want to convert my object into JSON so I implemented following code

    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 from app is

    {id: 9, name: GoldStar Classic 032, price: 1200, quantity: 1, attributes: {}, conditions: []}}
    

    Screenshot JSON from app

    But JSON from DartPad is

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

    Screenshot JSON from DartPad console

    How can I get same output on my app. please help. Also why is it not similar on both DartPad and app?