android 中 Gson 和 Room 的 ID 问题(发送 json 给客户端)

Id problem with Gson and Room in android (Sending json to client)

我的 Gson 和 Room with id 有问题! 我使用 json(库 Gson 和 JSON)将数据发送到带有 Room 数据库实现的客户端(Android 应用程序),我将客户端数据发送到 android,ID 看起来像:

{"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,我该如何解决这个问题? 关于结构的其他描述:

超级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;
 }
}

和主要的 class 用于保存到数据库:

@Entity
public class Account extends SuperBean {
//other var...
}

房间插入 DAO :

 @Insert(onConflict = OnConflictStrategy.REPLACE)
    void insertFromServer(Account account);

我使用 JSON 使用保存 ID 将数据保存到房间数据库,在此之前我清除了帐户 table 但保存的对象 ID 是房间认为需要添加的。

选项 - 1:SuperBean 实体

中的 id 移除 autoGenerate = true
@Entity
public class SuperBean implements Serializable {
    @PrimaryKey
    public long id;

    ...
}

选项 - 2:autoGenerate 使用另一个变量,如 _id 并保持你想要的 id 作为它在您的 SuperBean 实体中

@Entity
public class SuperBean implements Serializable {
    @PrimaryKey(autoGenerate = true)
    public long _id;

    public long id;

    ...
}