Generate toJson()

This commit is contained in:
Tobe O 2018-02-27 20:49:14 -05:00
parent 92a6ea8c30
commit ea298d4362
3 changed files with 27 additions and 2 deletions

View file

@ -15,7 +15,7 @@ class JsonModelGenerator extends GeneratorForAnnotation<Serializable> {
await buildStep.resolver, true, autoIdAndDateFields != false);
var lib = new File((b) {
generateClass(ctx, b);
generateClass(ctx, b, annotation);
});
var buf = lib.accept(new DartEmitter());
@ -23,7 +23,8 @@ class JsonModelGenerator extends GeneratorForAnnotation<Serializable> {
}
/// Generate an extended model class.
void generateClass(BuildContext ctx, FileBuilder file) {
void generateClass(
BuildContext ctx, FileBuilder file, ConstantReader annotation) {
file.body.add(new Class((clazz) {
clazz
..name = ctx.modelClassNameRecase.pascalCase
@ -42,6 +43,18 @@ class JsonModelGenerator extends GeneratorForAnnotation<Serializable> {
generateConstructor(ctx, clazz, file);
generateCopyWithMethod(ctx, clazz, file);
// Generate toJson() method if necessary
var serializers = annotation.peek('serializers')?.listValue ?? [];
if (serializers.any((o) => o.toIntValue() == Serializers.json)) {
clazz.methods.add(new Method((method) {
method
..name = 'toJson'
..returns = new Reference('Map<String, dynamic>')
..body = new Code('return ${clazz.name}Serializer.toMap(this);');
}));
}
}));
}

View file

@ -60,6 +60,10 @@ class Author extends _Author {
createdAt: createdAt ?? this.createdAt,
updatedAt: updatedAt ?? this.updatedAt);
}
Map<String, dynamic> toJson() {
return AuthorSerializer.toMap(this);
}
}
class Library extends _Library {
@ -88,4 +92,8 @@ class Library extends _Library {
createdAt: createdAt ?? this.createdAt,
updatedAt: updatedAt ?? this.updatedAt);
}
Map<String, dynamic> toJson() {
return LibrarySerializer.toMap(this);
}
}

View file

@ -54,4 +54,8 @@ class Book extends _Book {
createdAt: createdAt ?? this.createdAt,
updatedAt: updatedAt ?? this.updatedAt);
}
Map<String, dynamic> toJson() {
return BookSerializer.toMap(this);
}
}