-
-
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!)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This should be rewritten
to