You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Android Retrofit调用REST API时动态键JSON如何映射为Java对象

解决方案

你遇到的是JSON外层为动态键值对的映射场景,有两种成熟的适配方案:

方案1:使用Map映射(适配动态键场景,优先推荐)

外层JSON本质是字符串为键、MyObject数组为值的键值对结构,直接用Map<String, List<MyObject>>作为Retrofit接口的返回类型即可,既可以完整保留TEST1、TEST2这类键名,也能正确解析对应的数据。

Retrofit接口示例:

public interface ApiService {
    @GET("你的接口请求路径")
    Call<Map<String, List<MyObject>>> getTestData();
}

请求成功后取数逻辑:

@Override
public void onResponse(Call<Map<String, List<MyObject>>> call, Response<Map<String, List<MyObject>>> response) {
    if (response.isSuccessful() && response.body() != null) {
        Map<String, List<MyObject>> result = response.body();
        // 遍历获取所有键和对应数据
        for (Map.Entry<String, List<MyObject>> entry : result.entrySet()) {
            String key = entry.getKey(); // 可拿到TEST1、TEST2等键值
            List<MyObject> dataList = entry.getValue(); // 对应键的MyObject列表
            // 后续业务处理
        }
    }
}

方案2:自定义响应实体类(适配固定键场景)

如果外层的TEST1、TEST2是固定不会新增的键,可以直接封装响应实体类,存取更便捷:

public class TestResponse {
    @SerializedName("TEST1")
    private List<MyObject> test1List;
    @SerializedName("TEST2")
    private List<MyObject> test2List;

    // 生成Getter、Setter方法
    public List<MyObject> getTest1List() { return test1List; }
    public void setTest1List(List<MyObject> test1List) { this.test1List = test1List; }
    public List<MyObject> getTest2List() { return test2List; }
    public void setTest2List(List<MyObject> test2List) { this.test2List = test2List; }
}

对应Retrofit接口返回类型改为Call<TestResponse>即可。

注意事项

你已经定义的MyObject需要确保内部字段名和JSON返回字段完全匹配,如果字段名不一致需要添加@SerializedName注解做映射,示例:

public class MyObject {
    private boolean delegate;
    private String unit;
    private String code;
    private boolean read;
    private boolean write;

    // 生成Getter、Setter方法即可
}

内容的提问来源于stack exchange,提问作者Frap

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 09:09:00