How to get JSON serialized string using Dart Seria

2019-06-15 18:38发布

问题:

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}"}

回答1:

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.



回答2:

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"}


回答3:

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.