Skip to content

Instantly share code, notes, and snippets.

@sethladd
Created August 5, 2014 21:07
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sethladd/34b0d812b29c3bfd9529 to your computer and use it in GitHub Desktop.
Save sethladd/34b0d812b29c3bfd9529 to your computer and use it in GitHub Desktop.
Looking at both a simple by-hand JSON serialization, and an "automatic" serialization via mirrors. Note: this is by design extremely limited and only for illustration in a mailing list thread. Your need are almost certainly different and will need something custom.
import 'dart:convert';
import 'package:smoke/smoke.dart' as smoke;
@MirrorsUsed(targets: const [SimpleWithMirrors, Simple], override: '*')
import 'dart:mirrors';
class Simple {
int id;
String name;
Simple();
Simple.fromJson(Map json)
: id = json['id'],
name = json['name'];
toJson() => {'id': id, 'name': name};
}
abstract class Serializable {
static fromJson(object, Map json) {
json.forEach((k, v) {
smoke.write(object, smoke.nameToSymbol(k), v);
});
return object;
}
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;
}
main() {
var simple = new Simple()
..id = 1
..name = 'simple';
var jsonString = JSON.encode(simple);
print(jsonString);
var s2 = new Simple.fromJson(JSON.decode(jsonString));
print(s2);
var s3 = new SimpleWithMirrors()
..id = 1
..name = 'simpleWithMirrors';
var map = s3.toJson();
print(map);
var newJson = JSON.encode(map);
var s4 = Serializable.fromJson(new SimpleWithMirrors(), JSON.decode(newJson));
print(s4);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment