使用 Gson 序列化时忽略主键

Ignore Primary key when serialize using Gson

我正在使用 GSON 为我的应用程序做一个 export/import 解决方案,并保存在 ExternalStorage 上。我想序列化除 PrimaryKey 之外的所有字段。反序列化并将项目添加到数据库时,我希望 PrimaryKey 自动生成。

我找到的一个解决方案是使用 @Transient 但这是一个好的解决方案还是有任何缺点?还有其他建议吗?

@Entity(tableName = "item")
data class Item(
    @ColumnInfo(name = "name") val name: String,
    @ColumnInfo(name = "data", typeAffinity = ColumnInfo.BLOB) val DataItem: FloatArray,
    @ColumnInfo(name = "created_at") var createdAt: Long = System.currentTimeMillis()
) {
    @Transient @PrimaryKey(autoGenerate = true) @ColumnInfo(name = "id") var id: Int = 0
}

我看到了一些副作用——瞬态 make filed 完全不可序列化(例如当在 bundle 中设置为 argument 时,假设你的 Item 将是 Serializable),不仅是为了GSON.

所以,我看到的一种可能性是为 GSON 添加 SerializationStrategy:

import android.arch.persistence.room.PrimaryKey
import com.google.gson.FieldAttributes
import com.google.gson.ExclusionStrategy
import com.google.gson.GsonBuilder
import com.google.gson.Gson


GsonBuilder()
    .addSerializationExclusionStrategy(object : ExclusionStrategy {
        override fun shouldSkipField(f: FieldAttributes): Boolean {
            return f.annotations.any { it is PrimaryKey }
        }

        override fun shouldSkipClass(aClass: Class<*>): Boolean {
            return false
        }
    }
).create()

但是,它不会序列化每个用 @PrimaryClass 注释的字段。另一种方法是使用 @Expose 和参数 serialize = false:

@Expose(serializable = false) @PrimaryKey var id: Int = 0

那么该归档将被排除在序列化之外。 您可以在此处查看 Expose 的文档:https://static.javadoc.io/com.google.code.gson/gson/2.6.2/com/google/gson/annotations/Expose.html