Skip to content

Instantly share code, notes, and snippets.

@xros
Last active December 26, 2021 14:51
Show Gist options
  • Save xros/366a145b6bbfebb7edea8704a6622267 to your computer and use it in GitHub Desktop.
Save xros/366a145b6bbfebb7edea8704a6622267 to your computer and use it in GitHub Desktop.
.fromJson & .toJson example in Dart
// .fromJson , .toJson example in Dart
// .fromJson convert a Map Object to an Instance
// .toJson convert an Instance to a Map Object
class Person {
Person({required this.name, required this.age});
String name;
int age;
factory Person.fromJson(Map<String, Object> json) {
final name = json['name'];
final age = json['age'];
if (name == null) {
throw UnimplementedError('Key name unimplemented');
}
if (age == null) {
throw UnimplementedError('Value age unimplemented');
}
if (name is String && age is int) {
return Person(name: name, age: age);
}
throw UnsupportedError('Invalid type name');
}
Map<String, Object> toJson() => {'name': name, 'age': age};
}
void main() {
var the_json_in_map = {
'name': 'Lucy',
'age': 48,
};
var person = Person.fromJson(the_json_in_map);
print(person);
var json = person.toJson();
print(json);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment