android - android 中 Gson 和 Room 的 ID 问题(将 json 发送到客户端)
问题描述
我对 Gson 和带有 id 的 Room 有疑问!我将带有 json(库 Gson 和 JSON)的数据发送到带有 Room 数据库实现的客户端(Android 应用程序),我将客户端数据发送到带有 id 的 android,如下所示:
{"map":{"date":"2020-01-15 15:13:42.0","botType":1,"botName":"ds","id":62,"userId":1,"accountKey":"dcab171a-b6cc-4583-b5fc-3e996100725a","status":0}}
我需要在客户端数据库中使用 id 准确保存,但是房间会为这个对象生成一个新的 id,我该如何解决这个问题?关于结构的其他描述:
超级班:
@Entity
public class SuperBean implements Serializable {
@PrimaryKey(autoGenerate = true)
public long id;
@TypeConverters(DateConverter.class)
public Date date = new Date();
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
}
以及保存到数据库的主要类:
@Entity
public class Account extends SuperBean {
//other var...
}
房间插入 DAO:
@Insert(onConflict = OnConflictStrategy.REPLACE)
void insertFromServer(Account account);
我使用 JSON 将数据保存到带有保存 ID 的房间数据库中,在此之前我清除了帐户表,但保存的带有房间认为需要添加的 ID 的对象。
解决方案
选项 - 1:autoGenerate = true
从id
您的SuperBean
实体中删除
@Entity
public class SuperBean implements Serializable {
@PrimaryKey
public long id;
...
}
选项 - 2:使用另一个变量,如_id
autoGenerate并保持您想要id
的,因为它在您的SuperBean
实体中
@Entity
public class SuperBean implements Serializable {
@PrimaryKey(autoGenerate = true)
public long _id;
public long id;
...
}
推荐阅读
- html - 使用 Bootstrap 4 设计发票表单
- javascript - 如何在画布背景上显示 DIV
- node.js - 在 firebase 函数中设置 dotenv
- sql - 如何在此案例语句中处理除以零
- php - 如何将概率放入多个项目的随机生成中?
- google-sheets - 在发生特定时间后,如何将特定值替换为另一个值?
- javascript - 如何使用NodeJS中的firebase云功能从firebase实时数据库中找出最近的位置LatLng
- docker - 增加 docker pull 超时
- sql - Excel VBA - 动态范围
- rust - Rust 中元组的求值顺序是什么?