Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to stringify json in flutter

Tags:

json

flutter

dart

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?

like image 347
Mehdi Khademloo Avatar asked Feb 01 '19 21:02

Mehdi Khademloo


People also ask

What is JSON Stringify () method?

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.

Can you JSON Stringify a string?

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.


1 Answers

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"}
}
like image 152
dominicm00 Avatar answered Sep 21 '22 00:09

dominicm00