如何为Gson反序列化创建通用类

问题描述 投票:0回答:1

具有json,

{
  "owner": {
  "name": "frank",
  "address": "some street",
  "city": "a city"
  },
  "employees": [
    {
      "name": "todd",
      "address": "some street2",
      "city": "a city2",
      "title": "manager"
    },
    {
      "name": "micheal",
      "address": "some street3",
      "city": "a city3",
      "title": "engineer"
    }
  ],
  "partner": {
    "name": "ford",
    "address": "some street a",
    "city": "Magdeburg",
    "employees": [
      {
        "name": "marina",
        "address": "some street2",
        "city": "a city2",
        "title": "sectary"
      }
    ]
  }
}

使用POJO工具获取用于反序列化为类的数据模型,至少看到那里>

"name", "address", "city"

在json对象中很常见。

问题:如何在数据模型中使用通用的个人Person(val name:String,val address:String,val city:String)以使Gson反序列化?

@ApiSerializable
@Parcelize
data class Owner(
  @SerializedName("name")
  val name: String? = null,
  @SerializedName("address")
  val address: String? = null,
  @SerializedName("city")
  val city: String? = null
) : Parcelable

@ApiSerializable
@Parcelize
data class Employee(
  @SerializedName("name")
  val name: String? = null,
  @SerializedName("address")
  val address: String? = null,
  @SerializedName("city")
  val city: String? = null,
  @SerializedName("title")
  val title: String? = null

) : Parcelable

@ApiSerializable
@Parcelize
data class employees(
  @SerializedName("employees")
  val employees: List<Employee>? = null
) : Parcelable

@ApiSerializable
@Parcelize
data class Partner(
  @SerializedName("name")
  val name: String? = null,
  @SerializedName("address")
  val address: String? = null,
  @SerializedName("city")
  val city: String? = null,
  @SerializedName("employees")
  val employees: List<Employee>? = null
) : Parcelable

具有json,{“所有者”:{“名称”:“坦率”,“地址”:“某条街道”,“城市”:“一个城市”},“员工”:[{“名称”:“ todd”,“地址”:“ some street2”,“ city”:“ a ...

gson
1个回答
0
投票

可以在超类中提取公共字段,然后在需要时扩展这些类。

© www.soinside.com 2019 - 2024. All rights reserved.