我使用json_serializable库和firebase作为数据库。我需要将数据类序列化和反序列化为JSON。但firebase json格式看起来像这样
{
'some_id_here': {
'title': 'some_title',
'content': 'some_content',
'timestamp': 'some_timestamp'
}, ...
}
这是我的课
import 'package:json_annotation/json_annotation.dart';
part 'update.g.dart';
@JsonSerializable()
class Update {
final String id, title, content, timestamp;
Update({this.id, this.title, this.content, this.timestamp});
factory Update.fromJson(Map<String, dynamic> json) => _$UpdateFromJson(json);
Map<String, dynamic> toJson() {
return _$UpdateToJson(this);
}
}
那么如何自定义toJson()函数以便我可以反序列化
Update('ID', 'TITLE', 'CONTENT', 'TIMESTAMP');
至
{
'ID': {
'title': 'TITLE',
'content': 'CONTENT',
'timestamp': 'TIMESTAMP'
}
}
试试这个
class ID {
String title;
String content;
String timestamp;
Map<String, dynamic> toJson() {
final Map<String, dynamic> ID = new Map<String, dynamic>();
ID['title'] = this.title;
ID['content'] = this.content;
ID['timestamp'] = this.timestamp;
return ID;
}
}