【问题标题】:Ignore Primary key when serialize using Gson使用 Gson 序列化时忽略主键
【发布时间】:2019-10-09 07:12:43
【问题描述】:

我正在使用 GSON 为我的应用程序执行导出/导入解决方案,并节省 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
}

【问题讨论】:

    标签: android kotlin gson android-room


    【解决方案1】:

    我看到了一些副作用 - 临时 make 文件完全不可序列化(例如,当在 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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-26
      • 2016-01-22
      • 2016-07-26
      • 1970-01-01
      • 2020-07-23
      • 1970-01-01
      • 2011-10-22
      相关资源
      最近更新 更多