我的 Gson 和 Room 的 id 有问题! 我使用 Room 数据库实现将带有 json(库 Gson 和 JSON)的数据发送到客户端(Android 应用程序),我将客户端数据发送到带有 ids 的 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,我该如何解决此问题? 其他结构说明:
父类(super class):
@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:从 SuperBean
实体的 id
中删除 autoGenerate = true
@Entity
public class SuperBean implements Serializable {
@PrimaryKey
public long id;
...
}
选项 - 2:使用另一个变量(如_id
)进行自动生成,并保持您想要的id
不变在您的 SuperBean
实体
@Entity
public class SuperBean implements Serializable {
@PrimaryKey(autoGenerate = true)
public long _id;
public long id;
...
}
关于android - android中Gson和Room的ID问题(发送json到客户端),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59930674/