使用room後感覺上手還挺好的,就是遇到了個轉換器的問題
其實我就想保存外層List數據在數據庫,裏面List數據也是很重要的,想保存在一個表,裏層只能先保存jsonString形式了,然後就遇到轉換器的問題。
數據模型:
public class MyBean {
private List<DataBean> data;
public List<DataBean> getData() {
return data;
}
public void setData(List<DataBean> data) {
this.data = data;
}
@Entity(tableName = "data_table")
@TypeConverters({ AConverts.class, BConverts.class })
public static class DataBean implements Serializable {
@PrimaryKey
private long id;
private long account_id;
@ColumnInfo(name = "a_column")
private List<A> aList;
@ColumnInfo(name = "b_column")
private List<B> bList;
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public long getAccountId() {
return id;
}
public void setAccountId(long account_id) {
this.account_id = account_id;
}
public List<A> getA() {
return aList;
}
public void setA(List<A> aList) {
this.aList = aList;
}
public List<B> getB() {
return bList;
}
public void setB(List<B> bList) {
this.bList = bList;
}
public static class A {
private int start_time;
public int getStart_time() {
return start_time;
}
public void setStart_time(int start_time) {
this.start_time = start_time;
}
}
public static class B {
private int weekday;
public int getWeekday() {
return weekday;
}
public void setWeekday(int weekday) {
this.weekday = weekday;
}
}
}
}
轉換器
public class AConverts {
@TypeConverter
public List<DataBean.A> stringToObject(String value) throws IXJsonErrorException {
Gson gson = new Gson();
if (value == null) {
return Collections.emptyList();
}
Type listType = new TypeToken<List<DataBean.A>>() {}.getType();
return gson.fromJson(value, listType);
}
@TypeConverter
public String objectToString(List<DataBean.A> aList) {
Gson gson = new Gson();
return gson.toJson(aList);
}
}
public class BConverts {
@TypeConverter
public List<DataBean.B> stringToObject(String value) throws IXJsonErrorException {
Gson gson = new Gson();
if (value == null) {
return Collections.emptyList();
}
Type listType = new TypeToken<List<DataBean.B>>() {}.getType();
return gson.fromJson(value, listType);
}
@TypeConverter
public String objectToString(List<DataBean.B> bList) {
Gson gson = new Gson();
return gson.toJson(bList);
}
}
如果使用泛型添加一個通用的轉換器則會報錯
這個才兩個轉換器
我的項目中其實有四個,這個豈不是要寫死我。。。。。
如果新添加需要轉換器的類豈不是又要寫。。。。
有沒有遇到同樣痛苦的同學,歡迎留言探討