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?
The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
Use the JavaScript function JSON.stringify() to convert it into a string. const myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.
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"}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With