我不確定多型是否是正確的術語,所以我很抱歉。
我正在使用以下 API:
請求正文:
{
"user_id": "user_id",
"command": "submit_document",
}
回應:
{
"result": "success",
"code": 200,
"status": "ok",
"screen": "documents_rejected", // This is unique for different `data`
"next_screen": "",
"message": "Successful",
"data": {
// `data` is always a json object with known fields and parameters
}
}
我為不同型別的data回應準備了資料類,例如:
data class PhoneData(
@SerializedName("phone_number")
val phoneNumber: String? = null,
@SerializedName("phone_status")
val phoneStatus: String? = null
)
用于"screen": "phone"另一個螢屏的以下內容:
data class Data(
val deepLink: String? = null
)
問題是,在開始時,我必須發出以下請求來檢索當前螢屏:
{
"user_id": "user_id",
"command": "get_current_screen",
}
它回傳與上面類似的回應:
{
"result": "success",
"code": 200,
"status": "ok",
"screen": "main_screen", // Different types of screen types are known.
"next_screen": "",
"message": "Successful",
"data": {
// `data` is always a json object but the object could contain anything depending on the `screen` type.
}
}
但是資料欄位可以包含任何內容,具體取決于 screen
data class SplashScreenData(
// How do I make this data class combine all other data classes? One ugly approach is to add all the fields from different `data` classes here and use this one only.
)
I found about the RuntimeTypeAdapterFactory for polymorphic cases but am not sure how to make it work when there's no "type" like field within the data object (screen is unique but it's outside the data object).
It would be very helpful if someone has a solution or could point me in a direction.
uj5u.com熱心網友回復:
val frameTextReceived: String = frame.readText()
val jsonObject = JsonParser.parseString(frameTextReceived).asJsonObject
val type = when (jsonObject.get("type").asString) {
TYPE_JOIN_ROOM -> JoinRoom::class.java
TYPE_GAME_MOVE -> GameMove::class.java
TYPE_DISCONNECT_REQUEST -> DisconnectRequest::class.java
else -> BaseModel::class.java
}
val payload = gson.fromJson(frameTextReceived, type)
這是我的解決方案,在這里我有type引數,我可以通過它知道我必須在哪個類中反序列化物件,但在您的情況下,您有screen引數,您可以使用它。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/362395.html
