首页 > 解决方案 > 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 的对象。

标签: androidgsonandroid-room

解决方案


选项 - 1:autoGenerate = trueid您的SuperBean实体中删除

@Entity
public class SuperBean implements Serializable {
    @PrimaryKey
    public long id;

    ...
}

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

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

    public long id;

    ...
}

推荐阅读