Dart JSON Decoder Dart JSON Decoder dart dart

Dart JSON Decoder


Your best option is to use the Smoke library.

It's a subset of the Mirrors functionality but has both a Mirrors-based and a Codegen-based implementation. It's written by the PolymerDart team, so it's as close to "Official" as we're going to get.

While developing, it'll use the Mirrors-based encoding/decoding; but for publishing you can create a small transformer that will generate code.

Seth Ladd created a code sample here, which I extended slightly to support child-objects:

abstract class Serializable {  static fromJson(Type t, Map json) {    var typeMirror = reflectType(t);    T obj = typeMirror.newInstance(new Symbol(""), const[]).reflectee;    json.forEach((k, v) {      if (v is Map) {        var d = smoke.getDeclaration(t, smoke.nameToSymbol(k));        smoke.write(obj, smoke.nameToSymbol(k), Serializable.fromJson(d.type, v));      } else {        smoke.write(obj, smoke.nameToSymbol(k), v);      }    });    return obj;  }  Map toJson() {    var options = new smoke.QueryOptions(includeProperties: false);    var res = smoke.query(runtimeType, options);    var map = {};    res.forEach((r) => map[smoke.symbolToName(r.name)] = smoke.read(this, r.name));    return map;  }}

Currently, there is no support to get generic type information (eg. to support List) in Smoke; however I've raised a case about this here:

https://code.google.com/p/dart/issues/detail?id=20584

Until this issue is implemented, a "good" implementation of what you want is not really feasible; but I'm hopeful it'll be implemented soon; because doing something as basic as JSON serialisation kinda hinges on it!


I haven't had the time to complete it yet but dartson is currently working using mirrors. However a better solution would be using a transformer when compiling to JavaScript. https://pub.dartlang.org/packages/dartson