場景
在Android中使用Room進行存儲數據庫時提示:
Cannot figure out how to save this field into database. You can consider adding a type converter for
注:
博客:
https://blog.csdn.net/badao_liumang_qizhi
關注公眾號
霸道的程序猿
獲取編程相關電子書、教程推送與免費下載。
實現
這是因為Room中不支持對象中直接存儲集合。
下面是要存儲的對象Bean
@Entity public class ChatBean { private String msg; private int code; @NonNull @PrimaryKey private String id = ""; private List<ChatItem> data; @Entity public static class ChatItem { @PrimaryKey private int id; private String msgNum; private String content; //語音消息服務器地址 private String remoteContent; private String sender; private String receiver; private String type; private boolean canReceived; private String sendTime; private String receivedTime; //語音時長 private int voiceDuration; private boolean isRead; } }
上面省略了get和set方法,在bean中還有個 對象集合data,對象為ChatItem
所以需要新建一個轉換類ChatItemConverter
名字根據自己業務去定
package com.bdtd.bdcar.database; import androidx.room.TypeConverter; import com.bdtd.bdcar.bean.ChatBean; import com.bdtd.bdcar.common.GsonInstance; import com.google.gson.reflect.TypeToken; import java.lang.reflect.Type; import java.util.List; public class ChatItemConverter { @TypeConverter public String objectToString(List<ChatBean.ChatItem> list) { return GsonInstance.getInstance().getGson().toJson(list); } @TypeConverter public List<ChatBean.ChatItem> stringToObject(String json) { Type listType = new TypeToken<List<ChatBean.ChatItem>>(){}.getType(); return GsonInstance.getInstance().getGson().fromJson(json, listType); } }
此轉換類的功能是實現對象與json數據的轉換。
為了使用方便,這里將gson抽離出單例模式
所以新建GsonInstance
package com.bdtd.bdcar.common; import com.google.gson.Gson; public class GsonInstance { private static GsonInstance INSTANCE; private static Gson gson; public static GsonInstance getInstance() { if (INSTANCE == null) { synchronized (GsonInstance.class) { if (INSTANCE == null) { INSTANCE = new GsonInstance(); } } } return INSTANCE; } public Gson getGson() { if (gson == null) { synchronized (GsonInstance.class) { if (gson == null) { gson = new Gson(); } } } return gson; } }
然后轉換類新建完成。
在上面的實體bean,ChatBean上面添加注解。
@TypeConverters(ChatItemConverter.class)