【问题标题】:Gson is not serializing a predefined fieldGson 没有序列化预定义的字段
【发布时间】:2018-08-27 13:17:39
【问题描述】:

__type 字段未在 JSON 请求中序列化。虽然 java 版本一切正常。即使我将它放在具有默认值的构造函数或 init 块中也是一样的。我需要这个字段始终是字符串“文件”,但它显然是空的。

@Parcelize
data class File(var url: String?,
                var name: String?) : Parcelable {
    private var __type = "File"
}

与以下代码相同

@Parcelize
data class File(
        @SerializedName("url") var url: String?,
        @SerializedName("name") var name: String?,
        @SerializedName("__type") var type: String = "File") : Parcelable

JSON

{  
    "name":"sample_name.jpg",
    "url":"https://images.com/1123.jpg"
}

【问题讨论】:

  • 为什么不把 __type 也放入构造函数中呢?
  • @Ayusch 请再读一遍我写的内容。
  • 我违反了什么规则才能被否决?

标签: android json kotlin gson


【解决方案1】:

试试这个,

class File{
    @SerializedName("name")
    public var name: String? = null
    @SerializedName("url")
    public var url: String? = null
}

【讨论】:

    【解决方案2】:

    您可以在文档中找到使用@Parcelize注解时,只会序列化主构造函数参数:

    Instructs the Kotlin compiler to generate `writeToParcel()`, `describeContents()`
    [android.os.Parcelable] methods, as well as a `CREATOR` factory class automatically.
    
    The annotation is applicable only to classes that implements
    [android.os.Parcelable] (directly or indirectly).
    Note that only the primary constructor properties will be serialized.
    

    【讨论】:

    • 与构造函数中的字段相同。
    • 这个@SerializedName 可能有问题?尝试使用与 json 中相同的字段名称。
    • 由于某种原因该字段为空,尽管有默认值
    • 我认为@Parcelize 注释本身可能存在问题,编译器没有考虑默认字段值,因为它是一个实验性功能。
    • 切换回java。问题消失了。
    猜你喜欢
    • 2020-07-19
    • 2011-12-30
    • 1970-01-01
    • 2016-11-08
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 1970-01-01
    • 2016-05-30
    相关资源
    最近更新 更多