room不能存储列表,需要定义转换器converter
如果没有定义,抛错如下:
错误: Entities and Pojos must have a usable public constructor. You can have an empty constructor or a constructor whose parameters match the fields (by name and type).
public final class CommentList {
1:在表CommentList中有子评论commentChild列表
给它定义converter
import androidx.room.TypeConverter
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.hao.forum.bean.CommentChild
class CommentChildConvert {
@TypeConverter
fun stringToObject(value: String): List<CommentChild> {
val listType = object : TypeToken<List<CommentChild>>() {
}.type
return Gson().fromJson(value, listType)
}
@TypeConverter
fun objectToString(list: List<CommentChild>): String {
val gson = Gson()
return gson.toJson(list)
}