Created
May 19, 2020 19:18
-
-
Save ezzabuzaid/7bde42ac7c3b42f6c8a035f822af719c to your computer and use it in GitHub Desktop.
Dart automapper to serialize and deserialize JSON
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:mirrors'; | |
class Person { | |
String firstname; | |
String lastname; | |
} | |
main() { | |
final json = {"firstname": "ezz", "lastname": "abuzaid"}; | |
Person person = deserialize(json, Person); | |
final serializedJson = serialize(person); | |
print(serializedJson); | |
} | |
serialize(instance) { | |
final json = {}; | |
final instanceMirror = reflect(instance); | |
for (final m in instanceMirror.type.declarations.values) { | |
final name = MirrorSystem.getName(m.simpleName); | |
try { | |
json[name] = instanceMirror.getField(Symbol(name)).reflectee; | |
} catch (e) {} | |
} | |
return json; | |
} | |
deserialize<T>(Map<String, dynamic> json, Type type) { | |
final instance = reflectClass(type).newInstance(Symbol(''), []).reflectee; | |
final instanceMirror = reflect(instance); | |
for (final m in instanceMirror.type.declarations.values) { | |
final name = MirrorSystem.getName(m.simpleName); | |
if (json[name] != null) { | |
instanceMirror.setField(Symbol(name), json[name]); | |
} | |
} | |
return instance; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment