android - 使用 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 中获取值。
解决方案
使用@SerializedName("message") val message: String 等等。
推荐阅读
- c - 如何从 DER 或 PEM 文件中获取字符数组或字节数组中的值?
- google-sheets-formula - Google 表格 - 特定日期的化合物 FV
- flutter - Flutter 主异常超时
- django - 序列化对象字段Django的问题
- sql-server - 播放框架进化脚本错误行号
- c++ - 计算一系列数字中 3 的数量
- c - 如何将 go slice 复制到 c 指针中
- python - 没有库的python中的货架对象
- node.js - 如何用 fetch api 正确替换 axios api 并映射 nodeJS 中接收到的数据?
- azure - 检测 Azure blob 中的新文件并将该条目插入(调用 sp proc)到 azure sql