How to get JSON serialized string using Dart Serialization How to get JSON serialized string using Dart Serialization dart dart

How to get JSON serialized string using Dart Serialization


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.


I think you want the dart:json package rather than serialization. The output from the serialization is JSON, but it's JSON of the serialized structures and it's worrying about things like handling cycles that are overkill for what you're looking at. With the basic json package you can implement a toJson() method that will do the transformation and basic system objects are handled automatically. That has the advantage of not requiring mirrors, so it will work on the current dartj2s. Or you can use json_object as in the previous answer.