Skip to content

Instantly share code, notes, and snippets.

@ezzabuzaid
Created May 19, 2020 19:18
Show Gist options
  • Save ezzabuzaid/7bde42ac7c3b42f6c8a035f822af719c to your computer and use it in GitHub Desktop.
Save ezzabuzaid/7bde42ac7c3b42f6c8a035f822af719c to your computer and use it in GitHub Desktop.
Dart automapper to serialize and deserialize JSON
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