Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get JSON serialized string using Dart Serialization

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}"}
like image 246
Tusshu Avatar asked Dec 19 '12 15:12

Tusshu


People also ask

What is JSON serialization dart?

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.


2 Answers

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"}
like image 78
Seth Ladd Avatar answered Oct 24 '22 07:10

Seth Ladd


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.

like image 41
Eduardo Copat Avatar answered Oct 24 '22 08:10

Eduardo Copat