如何在flatter中将对象列表编码为Json?
我有一个类a,它包含另一个类B(合成)的对象列表。现在,我想将类A的对象存储到sqlite数据库中。我学会了如何将基本字符串或整数编码为json,但仍然找不到编码对象列表的方法 需要保存一个具体的“布局”对象如何在flatter中将对象列表编码为Json?,json,sqlite,flutter,dart,Json,Sqlite,Flutter,Dart,我有一个类a,它包含另一个类B(合成)的对象列表。现在,我想将类A的对象存储到sqlite数据库中。我学会了如何将基本字符串或整数编码为json,但仍然找不到编码对象列表的方法 需要保存一个具体的“布局”对象 class MallardDuck extends Duck { var image = "https://image.shutterstock.com/image-vector/cartoon-duck-swimming-600w-366901346.jpg";
class MallardDuck extends Duck {
var image = "https://image.shutterstock.com/image-vector/cartoon-duck-swimming-600w-366901346.jpg";
Widget d_widget;
List<Widget> previous_states = [];
List<Widget> redo_states = [];
}
类MallardDuck扩展了Duck{
var图像=”https://image.shutterstock.com/image-vector/cartoon-duck-swimming-600w-366901346.jpg";
小部件d_小部件;
列出以前的州=[];
列出重做状态=[];
}
抽象类布局扩展{
listOfDucks=[];
bool默认_布局;
}
这可能会对您有所帮助。
这不是你具体案例的答案,但希望这段代码能帮助你了解我是如何在另一个课堂上做到这一点的
class BlogData {
final String title;
final String associatedBusinessId;
final String category;
final List<BlogParagraph> blogParagraphs;
BlogData(
{this.title,
this.associatedBusinessId,
this.category,
this.blogParagraphs});
Map<String, dynamic> toJson() {
return {
'title': this.title,
'associatedBusinessId': this.associatedBusinessId,
'category': this.category,
'blogParagraphs':
blogParagraphs.map((paragraph) => paragraph.toJson()).toList()
};
}
}
类博客数据{
最后的字符串标题;
与businessid关联的最终字符串;
最终字符串类别;
最后段落清单;
博客数据(
{这个标题,
这是associatedBusinessId,
这一类,,
本条(第})款;
映射到JSON(){
返回{
“title”:this.title,
'associatedBusinessId':this.associatedBusinessId,
“category”:this.category,
“博客段落”:
blogparges.map((段落)=>段落.toJson()).toList()
};
}
}
然后,在博客段落类中:
class BlogParagraph {
final int paragraphId;
final String content;
final Set<int> imageRefs;
BlogParagraph({this.paragraphId, this.content, this.imageRefs});
Map<String, dynamic> toJson() {
return {
'id': this.paragraphId,
'content': this.content,
'imageRefs': imageRefs.isEmpty ? [] : imageRefs.toList(),
};
}
}
类博客段落{
最后整型段落;
最终字符串内容;
最终设置图像参考;
blogparage({this.paragraphId,this.content,this.imageRefs});
映射到JSON(){
返回{
'id':this.paragraphId,
“content”:this.content,
“imageRefs”:imageRefs.isEmpty?[]:imageRefs.toList(),
};
}
}
由于您使用的是sqflite
数据库,因此更干净的方法是为每个类使用单独的表。然后通过迁移外键进行关联。除了sqlite之外,您还可以推荐其他方法吗?唯一的目的是保存应用程序的状态,当我重新启动时,它从我离开的地方开始。没有通用的方法将“对象”编码为JSON。to/fromJSON必须为每个类手工制作(有时带有机械辅助)。
class BlogParagraph {
final int paragraphId;
final String content;
final Set<int> imageRefs;
BlogParagraph({this.paragraphId, this.content, this.imageRefs});
Map<String, dynamic> toJson() {
return {
'id': this.paragraphId,
'content': this.content,
'imageRefs': imageRefs.isEmpty ? [] : imageRefs.toList(),
};
}
}