ior*_*i24 3 json gson kotlin retrofit moshi
编辑:
这是我拥有的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
}
Run Code Online (Sandbox Code Playgroud)
或者它可以来自服务器的任何json字符串。这里的要点是可能有1个或多个具有动态值的字段(这种情况下field3可以是字符串或整数)
然后我想将它们反序列化为任何POJO
class Temp1 {
// field1 here
// field2 here
@SerializedName("field3")
val field3Int: Int? = null
@SerializedName("field3")
val field3String: String? = null
}
Run Code Online (Sandbox Code Playgroud)
这意味着如果从服务器发送的值为an 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()
Run Code Online (Sandbox Code Playgroud)
有了它们,Moshi您就可以利用多态反序列化功能。只需编写一个将使用的自定义适配器即可JsonReader#readJsonValue()。参见下面的代码:
data class Multitype constructor(val fieldInt: Int?, val fieldString: String?) {
constructor(fieldInt: Int) : this(fieldInt, null)
constructor(fieldString: String) : this(null, fieldString)
}
class MultitypeJsonAdapterAdapter {
@FromJson fun fromJson(reader: JsonReader): Multitype {
val jsonValue = reader.readJsonValue() as Map<String, Any?>
val field = jsonValue["field"]
return when (field) {
is String -> Multitype(field)
is Double -> Multitype(field.toInt()) // readJsonValue parses numbers as Double
else -> throw JsonDataException("Expected a field of type Int or String")
}
}
@ToJson fun toJson(writer: JsonWriter, value: Multitype?) {
TODO("not implemented")
}
}
class MultitypeJsonAdapterAdapterTest {
@Test fun check() {
val moshi = Moshi.Builder()
.add(MultitypeJsonAdapterAdapter())
.add(KotlinJsonAdapterFactory())
.build()
val adapter = moshi.adapter(Multitype::class.java)
val fromJson1 = adapter.fromJson("""{ "field": 42 }""")
assertThat(fromJson1).isEqualTo(Multitype(42))
val fromJson2 = adapter.fromJson("""{ "field": "test" }""")
assertThat(fromJson2).isEqualTo(Multitype("test"))
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1077 次 |
| 最近记录: |