23

In flutter(dart), it is easy to deserialize Json and get a token from it, but when I try to serialize it again, the quotation marks around the keys and values with disappear.

String myJSON = '{"name":{"first":"foo","last":"bar"}, "age":31, "city":"New York"}';
var json = JSON.jsonDecode(myJSON); //_InternalLinkedHashMap
var nameJson = json['name']; //_InternalLinkedHashMap
String nameString = nameJson.toString();

Although the nameJson have all the double quotations, the nameString is

{first: foo, last: bar}

(true answer is {"first": "foo", "last": "bar"})

how to preserve Dart to remove the "s?

Mehdi Khademloo
  • 2,754
  • 2
  • 20
  • 40
  • I want a `json string` that can use again for `JsonDecoder`, when the quotation marks remove, the string is not a valid `json` no longer – Mehdi Khademloo Feb 01 '19 at 22:07

2 Answers2

51

When encoding the object back into JSON, you're using .toString(), which does not convert an object to valid JSON. Using jsonEncode fixes the issue.

import 'dart:convert';

void main() {
  String myJSON = '{"name":{"first":"foo","last":"bar"}, "age":31, "city":"New York"}';
  var json = jsonDecode(myJSON);
  var nameJson = json['name'];
  String nameString = jsonEncode(nameJson); // jsonEncode != .toString()
  print(nameString); // outputs {"first":"foo","last":"bar"}
}
dominicm00
  • 1,490
  • 10
  • 22
2

Let's say you have a map, and you want to stringify it into a string variable, then all what you need to do is:

Map<String, dynamic> map = {...};
String stringifiedString = jsonEncode(map);

The output will be:

"{\"name\":{\"first\":\"foo\",\"last\":\"bar\"}, \"age\":31, \"city\":\"New York\"}"

You can read more about this on the documentation page.

Osama Remlawi
  • 2,356
  • 20
  • 21