Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save DanTup/d0b486d276f49da93e74 to your computer and use it in GitHub Desktop.
Save DanTup/d0b486d276f49da93e74 to your computer and use it in GitHub Desktop.
+ support for child objects (sorry if it's bad; written in Notepad and don't really know Dart!)
import 'dart:convert';
import 'package:smoke/smoke.dart' as smoke;
@MirrorsUsed(targets: const [SimpleWithMirrors, Simple], override: '*')
import 'dart:mirrors';
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;
}
}
class SimpleWithMirrors extends Object with Serializable {
int id;
String name;
Child child;
}
class Child extends Object with Serializable {
int id;
}
main() {
var s4 = Serializable.fromJson(SimpleWithMirrors, JSON.decode('{"id":1,"name":"simple","child":{"id":2}}'));
print(JSON.encode(s4));
}
@zijam
Copy link

zijam commented Jul 15, 2015

This should be rewritten

T obj = typeMirror.newInstance(new Symbol(""), const[]).reflectee;

to

var obj = typeMirror.newInstance(new Symbol(""), const[]).reflectee; 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment