Gson未序列化预定义字段

时间:2018-08-27 13:17:39

标签: android json kotlin gson

__ type 字段未在JSON请求中序列化。虽然Java版本一切正常。即使我将其放在具有默认值的构造函数中或init块中,也是如此。我需要此字段始终为字符串“ File”,但显然它为null。

@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"
}

2 个答案:

答案 0 :(得分:0)

尝试一下

sealed trait Either[+L, +R] {
  def flatMap[B, M >: L](f: R => Either[M, B]): Either[M, B] = this match {
    case Left(e) => Left(e)
    case Right(e) => f(e)
  }
}

final case class Right[+A, +B](right: B) extends Either[A, B]
final case class Left[+A, +B](left: A) extends Either[A, B]

答案 1 :(得分:0)

您可以在文档中发现,使用@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.