24

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?

1
  • 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 Commented Feb 1, 2019 at 22:07

2 Answers 2

55

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

Comments

3

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.

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.