Created
August 5, 2014 21:07
-
-
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.
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'; | |
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