Skip to content

Instantly share code, notes, and snippets.

@lucperkins
Last active December 30, 2015 20:19
Show Gist options
  • Save lucperkins/7879987 to your computer and use it in GitHub Desktop.
Save lucperkins/7879987 to your computer and use it in GitHub Desktop.
I was looking for a good way to make sure that an object is properly constructed on the basis of a `fromJson` method. The only way to ensure this is to first ensure that the JSON object from which the object is being constructed has the same keys as required by the object's class. I've chosen to do this by constructing an abstract `CompatibleWit…
import 'dart:convert';
abstract class CompatibleJson {
Map<String, dynamic> get attributes;
bool jsonCompatible(Map<String, dynamic> json) {
return (json.keys.length == attributes.keys.length) &&
(json.keys.every((String key) => key.runtimeType == String)) &&
(json.keys.every((String key) => attributes.keys.contains(key)) &&
(json.values.every((dynamic value) => attributes.values.runtimeType == value.runtimeType));
}
String inspectJson() => JSON.encode(attributes);
}
class Person extends CompatibleJson {
String name;
int age;
Map<String, dynamic> get attributes => { 'name': name, 'age': age };
Person(this.name, this.age);
Person.fromJson(Map<String, dynamic> json) {
if (jsonCompatible(json)) {
name = json['name'];
age = json['age'];
} else {
throw('Incompatible JSON');
}
}
}
void main() {
Person luc = new Person.fromJson({ 'foo': 'bar' }); /// Throws 'Incompatible JSON' error
Person luc = new Person.fromJson({ 'name': 'Luc', 'age': 31, 'foo': 'bar' }); /// Throws 'Incompatible JSON' error again due to the presence of the third argument
Person luc = new Person.fromJson({ 'name': 'Luc', 'age': 31 }); /// Works properly
print(luc.inspectJson()); /// {"name":"Luc","age":31}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment