For the following code
var address = new Address();
address.street = 'N 34th';
address.city = 'Seattle';
var serialization = new Serialization()
..addRuleFor(address);
String output = serialization.write(address);
How do i get a json output like this:
address: {'street':'N 34th', 'city':'Seattle'}
Output generated by above code is as follows:
{"roots":[{"__Ref":true,"rule":3,"object":0}],"data":[[],[],[],[["Seattle","N 34th"]]],"rules":"{\"roots\":[{\"__Ref\":true,\"rule\":1,\"object\":0}],\"data\":[[],[[{\"__Ref\":true,\"rule\":4,\"object\":0},{\"__Ref\":true,\"rule\":3,\"object\":0},{\"__Ref\":true,\"rule\":5,\"object\":0},{\"__Ref\":true,\"rule\":6,\"object\":0}]],[[],[],[\"city\",\"street\"]],[[]],[[]],[[]],[[{\"__Ref\":true,\"rule\":2,\"object\":0},{\"__Ref\":true,\"rule\":2,\"object\":1},\"\",{\"__Ref\":true,\"rule\":2,\"object\":2},{\"__Ref\":true,\"rule\":7,\"object\":0}]],[\"Address\"]],\"rules\":null}"}
The JSON (JavaScript Object Notation) is a kind of data format that encodes an object into a string. This kind of data can be easily translated between server and browser, and server to server. Serialization is a process that converts an object into the same string.
It turns out that the dart:json
library makes this very easy. You need to implement toJson
in your class to make it work.
For example:
class Address {
String street;
String city;
Map toJson() {
return {"street": street, "city": city};
}
}
main() {
var addr = new Address();
addr.street = 'N 34th';
addr.city = 'Seattle';
print(JSON.stringify(addr));
}
Which will print out:
{"street":"N 34th","city":"Seattle"}
You can use the JsonObject for Dart, add this to your pubspec.yaml
file and then run pub install
(Tools -> Pub Install)
dependencies:
json_object:
git: git://github.com/chrisbu/dartwatch-JsonObject.git
And then change your code to call objectToJson
:
import 'package:json_object/json_object.dart';
var address = new Address();
address.street = 'N 34th';
address.city = 'Seattle';
String output = objectToJson(address);
Note that objectToJson
requires mirrors support (the reflection capabilities) which only work in Dart VM at the moment. It does not work in dart2js as of 2012-12-20.
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