Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
111 views
in Technique[技术] by (71.8m points)

android - Multi type object in kotlin

from an API call i get as response a body with this structure

open class BaseResponseEntity {

    @SerializedName("result")
    val result: ResultEnum = ResultEnum.NONE

    @SerializedName("errorCode")
    val errorCode: String = ""

    @SerializedName("errorMessage")
    val errorMessage: String = ""

    @SerializedName("successMessage")
    val successMessage: String = ""

    @SerializedName("value") 
    val code: LastPaymentCodeModel?

}

where the field "value" can be three types: null, String or LastPaymentCodeModel. How can i get this? I managed to put a ? so that both null and LastPaymentCodeModel are handled, but i don't know how to handle the String type too.

question from:https://stackoverflow.com/questions/65903492/multi-type-object-in-kotlin

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think the best approach would probably be to use type Any? for code. Then you should write a custom GSon serializer/deserilizer (JsonDeserializer<BaseResponseEntity>) for the BaseResponseEntity object.

In this Json deserializer, you would need to check the type of value (e.g is it a string or a data structure) and decode it to the correct object type.

Alternative, to avoid the use of Any?, you could leave the model exactly as you have it. You will still need to write a custom JsonDeserializer, however if value is a string then it would still create a LastPaymentCodeModel, using the string value as one of it's properties.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...