簡體   English   中英

如何使用 Retrofit ZE84E30B9390CDB64DB6ZDB2CAB9DZ 本身在 model class 中自定義實際響應

[英]How can I customise the actual response in model class itself using Retrofit Android?

我正在通過一個示例進行解釋,因此請嘗試理解以下情況:

假設從 API 我收到了以下回復:

{
  "data": {
    "hot": [
      {
        "name": "OnePlus 6 (Mirror Black 6GB RAM + 64GB memory)",
        "price": "34999",
        "image_url": "https://images-eu.ssl-images-amazon.com/images/I/41DZ309iN9L._AC_US160_.jpg",
        "key": 2
      }
    ],
    "cold": [
      {
        "name": "OnePlus 6 (Mirror Black 6GB RAM + 64GB memory)",
        "price": "34999",
        "image_url": "https://images-eu.ssl-images-amazon.com/images/I/41DZ309iN9L._AC_US160_.jpg",
        "value": 4
      }
    ],
    "widget": {
      "test": "Hello"
    }
  }
}

現在,通常使用 Retrofit + GSON,我們使用 model 類,如下所示:

溫度

    data class Temperature(
    val `data`: Data
)

數據

    data class Data(
    val cold: List<Cold>,
    val hot: List<Hot>,
    val widget: Widget
)

寒冷的

data class Cold(
    val image_url: String,
    val name: String,
    val price: String,
    val value: Int
)

熱的

data class Hot(
    val image_url: String,
    val key: Int,
    val name: String,
    val price: String
)

小部件

data class Widget(
    val test: String
)

要求

我想要的是,我的 model class 應該設計不同。 如果我像這樣創建自定義 class :

小部件

data class Widget(
    val map: LinkedHashMap<Int, Int>
)

在這個 map 里面,使用 Retrofit,我想要:

map 密鑰應存儲為: Hot class “密鑰”字段

map 值應存儲為: Cold class “值”字段

請注意,我不想提取數據然后手動創建 map object,迭代循環並將其存儲在任何視圖或其他層 class 中。 我需要一些自動化的東西。 可以使用任何轉換器工廠嗎?

I don't know a way to get both the data class and HashMap representation of a response from Retrofit at the same time, but one solution you can try is to get the data classes from Retrofit and convert them to Maps by yourself whenever you need那。

要將數據 class 轉換為Map<String, Any>您可以使用任何序列化庫。 使用 Gson,您可以使用這些輔助函數:

val gson = GsonBuilder()
    .setObjectToNumberStrategy(ToNumberPolicy.LONG_OR_DOUBLE)
    .create()

//convert a data class to a map
fun <T> T.serializeToMap(): Map<String, Any> {
    return convert()
}

//convert a map to a data class
inline fun <reified T> Map<String, Any>.toDataClass(): T {
    return convert()
}

//convert an object of type I to type O
inline fun <I, reified O> I.convert(): O {
    val json = gson.toJson(this)
    return gson.fromJson(json, object : TypeToken<O>() {}.type)
}

用法:

val temperature = // Your Temperature data class that you received from Retrofit
val map = temperature.serializeToMap()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM