首页 > 解决方案 > 使用 Gson 和 Retrofit2 解析带有动态字段的 JSON

问题描述

我正在使用 Retrofit2 访问 API,但无法以灵活的方式将响应解析为对象。

API 响应采用以下通用格式:

Request: /api/users
Response:
{
    "success": true,
    "message": "Get all users",
    "users": [{
        "id": 1
        "name": "User Name"
    }]
}

Request: /api/user/1/items
Response:
{
    "success": true,
    "message": "Get all items",
    "items": [{
        "id": 1
        "name": "Item Name"
    }]
}

模型通常格式如下:

data class ApiResponse<T>(val success: Boolean,
                          val message: String,
                          val payload: T)
data class User(val id: String, val name: String)
data class Item(val id: String, val name: String)

我曾尝试使用 anokhttp3.Interceptor来解析响应,但我只是不知道如何处理动态键(用户、项目等)。我在发出请求时知道密钥,但我不确定如何将密钥传达给我的拦截器以便从 JSON 中获取值。

标签: androidkotlingsonretrofit2

解决方案


使用@SerializedName("message") val message: String 等等。


推荐阅读