I trying to save JSON to local database using moor.
JSON : {"status": true,"ABC": {"open": 5,"closed": 0},"DEF": {"open": 3,"category": {"typeA": 0}}}
JsonResponse
@JsonSerializable()
class JsonResponse{
var status;
var ABC = ABC();
var DEF = DEF();
JsonResponse();
factory JsonResponse.fromJson(Map<String, dynamic> json) =>
_$JsonResponseFromJson(json);
Map<String, dynamic> toJason() => _$JsonResponseToJson(this);
}
DEF
@JsonSerializable()
class DEF {
DEF();
var open;
var category = Category();
factory DEF.fromJson(Map<String, dynamic> json) =>
_$DEFFromJson(json);
Map<String, dynamic> toJason() => _$DEFToJson(this);
}
Category
@JsonSerializable()
class Category{
var typeA;
Category();
factory Category.fromJson(Map<String, dynamic> json) =>
_$CategoryFromJson(json);
Map<String, dynamic> toJason() => _$CategoryToJson(this);
My repo class
try {
response = await _service.getJason(id);
var jsonResponse = JsonResponse.fromJson(response.body);
await _dao.insert(JsonData(
abc: jsonResponse.ABC,
def: jsonResponse.DEF);
....
} catch (e) {
......
}
}
My database
class JsonTable extends Table {
TextColumn get abc =>
text().map(const ABCToSqlConverter()).nullable()();
TextColumn get def =>
text().map(const DEFToSqlConverter()).nullable()()
}
class DEFToSqlConverter
extends TypeConverter<DEF, String> {
const DEFToSqlConverter();
DEF mapToDart(String fromDb) {
if (fromDb == null) return null;
return DEF.fromJson(json.decode(fromDb));
}
String mapToSql(DEF def) =>
json.encode(def.toJason());
}
Error
Converting object to an encodable object failed: Instance of
'Category'
I see you're naming some of your methods toJason. When you're not calling that method manually, I think it has to be toJson for Dart's json converter to pick it up. So, def.toJason() implicitly tries to convert the Category instance to a json object. Since Category doesn't have a toJson() method, that fails.
I'd recommend renaming all toJason methods to toJson, this should fix the problem.
Thanks
Most helpful comment
I see you're naming some of your methods
toJason. When you're not calling that method manually, I think it has to betoJsonfor Dart's json converter to pick it up. So,def.toJason()implicitly tries to convert theCategoryinstance to a json object. SinceCategorydoesn't have atoJson()method, that fails.I'd recommend renaming all
toJasonmethods totoJson, this should fix the problem.