编辑:
这是我拥有的json字符串:
json#1
{
[
{
field1 : ""
field2 : 0
field3 : "Amount not fixed" or field : 250 // this field can be string or int
},
{
field1 : ""
field2 : 0
field3 : "Amount not fixed" or field : 250 // this field can be string or int
}
]
}
json#2
{
field1 : ""
field2 : 0
field3 : "Amount not fixed" or field : 250 // this field can be string or int
}
或者它可以来自服务器的任何 json 字符串。这里的要点是可能有 1 个或多个字段可能具有动态值(在这种情况下 field3 可以是字符串或 int)
然后我想将它们反序列化为任何 POJO
class Temp1 {
// field1 here
// field2 here
@SerializedName("field3")
val field3Int: Int? = null
@SerializedName("field3")
val field3String: String? = null
}
这意味着如果从服务器发送的值是Int
,我想将值设置为field3Int
。如果是String
,则设置为field3String
。
可能有其他 POJO 将具有这些可能具有动态值的字段。
感谢 Serj 的回答,但在我编辑问题以显示我的真实情况后,我仍然无法使其在 TypeAdapter 类上工作。
顺便提一句。我将它与 Retrofit2 一起使用,如下所示:
val moshi = Moshi.Builder()
.add(MultitypeJsonAdapterAdapter())
.build()
return Retrofit.Builder().baseUrl(baseUrl)
.addConverterFactory(MoshiConverterFactory.create(moshi))
.client(httpClient.build())
.build()