How can I made a JSON string out of a collection in dart, as I can do it with Maps. The docs say I can pass a map or a an array into the JSON.stringify()
method. But there are no Array data type in Dart and passing a collection gives me an exception.
I've a naive workaround, but I wonder if there will be a better way to do this:
String s = '[';
bool first=true;
_set.forEach(function(item){
if (first) {
first = false;
} else {
s+=',';
}
s += JSON.stringify(item);
});
s +=']';
print(s);
return s;
Stringify a JavaScript ObjectUse the JavaScript function JSON. stringify() to convert it into a string. const myJSON = JSON. stringify(obj);
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.
Then, use map on purchases property. For each element, returns the JSON object by using Purchase 's toJson method. Then, convert the map result to List<Map<String, dynamic>> by using toList (). That's how to serialize a Dart object to JSON object or string.
When you parse small JSON documents, your application is likely to remain responsive and not experience performance problems. But parsing very large JSON documents can result in expensive computations that are best done in the background on a separate Dart isolate. The official docs have a good guide about this:
In fact, jsonDecode () is a generic method that works on any valid JSON payload, regardless of what's inside it. All it does is decode it and return a dynamic value. But if we work with dynamic values in Dart we lose all the benefits of strong type-safety.
Stringify a JavaScript Object. Imagine we have this object in JavaScript: var obj = { name: "John", age: 30, city: "New York" }; Use the JavaScript function JSON.stringify () to convert it into a string. var myJSON = JSON.stringify(obj); The result will be a string following the JSON notation.
In Dart, you can get a JSON String
out of an Object
using the JsonEncoder
's convert
method. Here is an example:
import 'dart:convert';
void main() {
final jsonEncoder = JsonEncoder();
final collection1 = List.from([1, 2, 3]);
print(jsonEncoder.convert(collection1)); // prints [1,2,3]
final collection2 = List.from(['foo', 'bar', 'dart']);
print(jsonEncoder.convert(collection2)); // prints ["foo","bar","dart"]
final object = {'a': 1, 'b': 2};
print(jsonEncoder.convert(object)); // prints {"a":1,"b":2}
}
Passing a list works for me:
dart-sdk/lib/frog/server/dart_json.dart
json:dart
using this code:
void main() {
var list = new List.from(["a","b","c"]);
print(JSON.stringify(list));
}
prints this JSON snippet:
["a","b","c"]
Doesn't work for new Set.from(...)
which is expected, given that JSON only deals in maps and lists.
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