From c13b0ff17f03e384ae80af2f277a3357d26912b4 Mon Sep 17 00:00:00 2001 From: yohom <382146139@qq.com> Date: Thu, 14 Mar 2019 17:42:58 +0800 Subject: [PATCH] Add a `toJson` method for serialization. --- .../example/lib/database/database.g.dart | 16 ++++++++++++++++ .../lib/src/writer/data_class_writer.dart | 14 ++++++++++++++ 2 files changed, 30 insertions(+) diff --git a/moor_flutter/example/lib/database/database.g.dart b/moor_flutter/example/lib/database/database.g.dart index 8f684ee5..ffb1b5e4 100644 --- a/moor_flutter/example/lib/database/database.g.dart +++ b/moor_flutter/example/lib/database/database.g.dart @@ -23,6 +23,15 @@ class TodoEntry { category: intType.mapFromDatabaseResponse(data['category']), ); } + Map toJson() { + return { + 'id': id, + 'content': content, + 'targetDate': targetDate, + 'category': category, + }; + } + TodoEntry copyWith( {int id, String content, DateTime targetDate, int category}) => TodoEntry( @@ -128,6 +137,13 @@ class Category { description: stringType.mapFromDatabaseResponse(data['`desc`']), ); } + Map toJson() { + return { + 'id': id, + 'description': description, + }; + } + Category copyWith({int id, String description}) => Category( id: id ?? this.id, description: description ?? this.description, diff --git a/moor_generator/lib/src/writer/data_class_writer.dart b/moor_generator/lib/src/writer/data_class_writer.dart index 3a002615..462448a0 100644 --- a/moor_generator/lib/src/writer/data_class_writer.dart +++ b/moor_generator/lib/src/writer/data_class_writer.dart @@ -26,6 +26,9 @@ class DataClassWriter { // Also write parsing factory _writeMappingConstructor(buffer); + // And a serializer method + _writeToJson(buffer); + // And a convenience method to copy data from this class. _writeCopyWith(buffer); @@ -94,6 +97,17 @@ class DataClassWriter { buffer.write(');}\n'); } + void _writeToJson(StringBuffer buffer) { + buffer.write('Map toJson() {\n return {'); + + for (var column in table.columns) { + final getter = column.dartGetterName; + buffer.write('\'$getter\': $getter,'); + } + + buffer.write('};}'); + } + void _writeCopyWith(StringBuffer buffer) { final dataClassName = table.dartTypeName;