Last active
October 1, 2017 17:01
-
-
Save Ticore/d3dc861b85022c4059c79d2826951b89 to your computer and use it in GitHub Desktop.
dart json encoder/decoder
This file contains hidden or 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
/// | |
/// ## reference | |
/// | |
/// [JsonEncoder](https://api.dartlang.org/stable/1.24.2/dart-convert/JsonEncoder/JsonEncoder.html) | |
/// [JsonDecoder](https://api.dartlang.org/stable/1.24.2/dart-convert/JsonDecoder/JsonDecoder.html) | |
/// | |
/// [Vloz/JSON_Encode_Decode.dart](https://gist.github.com/Vloz/11363954) | |
/// [better reviver API for JsonDecoder #29750](https://github.com/dart-lang/sdk/issues/29750) | |
/// | |
/// | |
import "dart:convert"; | |
import "dart:mirrors"; | |
class JsonSerializable { | |
fromRaw(var raw) {} | |
toJson() => {}; | |
} | |
class Foo1 implements JsonSerializable { | |
String name; | |
fromRaw(var raw) { | |
this.name = raw['name']; | |
} | |
toJson() => {'name': this.name, '__type__': 'Foo1'}; | |
} | |
class Foo2 implements JsonSerializable { | |
String name; | |
fromRaw(var raw) { | |
this.name = raw['name']; | |
} | |
toJson() => {'name': this.name, '__type__': 'Foo2'}; | |
} | |
class Foo3 implements JsonSerializable { | |
String name; | |
fromRaw(var raw) { | |
this.name = raw['name']; | |
} | |
toJson() => {'name': this.name, '__type__': 'Foo3'}; | |
} | |
Map toEncodable(var obj) { | |
if (obj is JsonSerializable) { | |
return obj.toJson(); | |
} else { | |
return obj; | |
} | |
} | |
Object reviver(var key, var value) { | |
if (value is Map) { | |
var type = value['__type__']; | |
if (type != null) { | |
LibraryMirror lm = currentMirrorSystem().findLibrary(new Symbol('')); | |
ClassMirror classMirror = lm.declarations[new Symbol(type)]; | |
InstanceMirror insMirror = classMirror.newInstance(new Symbol(''), []); | |
insMirror.invoke(#fromRaw, [value]); | |
return insMirror.reflectee; | |
} | |
} | |
return value; | |
} | |
main() { | |
var jsonEncoder = new JsonEncoder(toEncodable); | |
var jsonDeocder = new JsonDecoder(reviver); | |
var foo1 = new Foo1()..name = 'Foo01'; | |
var foo2 = new Foo2()..name = 'Foo02'; | |
var foo3 = new Foo3()..name = 'Foo03'; | |
var originalData = [ | |
{'foo1': foo1}, | |
{'foo2': foo2}, | |
{'foo3': foo3}, | |
]; | |
var jsonStr = jsonEncoder.convert(originalData); | |
print('jsonStr: $jsonStr'); | |
var restoreData = jsonDeocder.convert(jsonStr); | |
print(originalData); | |
print(restoreData); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment