使用Gson进行序列化时忽略主键

时间:2019-10-09 07:12:43

标签: android kotlin gson android-room

我正在使用GSON为我的应用程序执行导出/导入解决方案,并保存在ExternalStorage上。我想序列化除PrimaryKey以外的所有字段。反序列化并将项目添加到db时,我希望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
}

1 个答案:

答案 0 :(得分:3)

我看到了一些副作用-瞬态make文件完全无法序列化(例如,在捆绑中设置为argument的情况下,假设您的ItemSerializable),不仅限于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