3

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?

4
  • You can create fromJson method in model class which return factory constructor Commented Apr 28, 2020 at 7:21
  • @AbhishekGhaskata correct me if I am wrong... fromJson is only to convert json to object right? I need only convert object to JSON. Commented Apr 28, 2020 at 7:23
  • Yes you are right I think you need type casting Commented Apr 28, 2020 at 7:25
  • @AbhishekGhaskata can you please share some code snippet so i could get some hint? Commented Apr 28, 2020 at 7:26

1 Answer 1

7

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":[]}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.