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

如何使用Retrofit 2.3.0解析JSON对象?含嵌套JSON解析需求

用Retrofit 2.3.0解析JSON对象及嵌套JSON指南

嘿,作为刚上手Retrofit的新手,我完全懂你现在的需求——当初我第一次啃嵌套JSON解析的时候也绕了不少弯路。下面我一步步给你讲清楚怎么搞定这个问题,尤其是你给出的那个嵌套结构的JSON。

第一步:添加必要依赖

首先得在你的项目里引入Retrofit 2.3.0和Gson转换器(Retrofit默认用Gson来做JSON序列化/反序列化)。如果是用Gradle的话,在build.gradle(Module级)里加这些依赖:

dependencies {
    // Retrofit核心库
    implementation 'com.squareup.retrofit2:retrofit:2.3.0'
    // Gson转换器
    implementation 'com.squareup.retrofit2:converter-gson:2.3.0'
}

第二步:创建对应的数据类(POJO)

Retrofit靠数据类来映射JSON结构,你得根据给定的JSON层级来创建类,保证字段名和JSON里的键对应(如果命名不一样可以用@SerializedName注解,不过尽量保持一致更省心)。

针对你提供的JSON,我们需要3个类:

  1. 最外层的响应类(用来包裹整个JSON)
  2. main对应的类
  3. row数组里的每个元素对应的类

Java代码示例:

// 最外层响应类
public class ApiResponse {
    private MainData main;

    // Getter和Setter方法,也可以用Lombok简化编写
    public MainData getMain() {
        return main;
    }

    public void setMain(MainData main) {
        this.main = main;
    }
}

// main字段对应的类
public class MainData {
    private String totalResults;
    private String libelleCategory;
    private String libelleSubCategory;
    private String idCategory;
    private String idSubCategory;
    private List<RowItem> row;

    // Getter和Setter方法
    public String getTotalResults() {
        return totalResults;
    }

    public void setTotalResults(String totalResults) {
        this.totalResults = totalResults;
    }

    public String getLibelleCategory() {
        return libelleCategory;
    }

    public void setLibelleCategory(String libelleCategory) {
        this.libelleCategory = libelleCategory;
    }

    // 其他字段的Getter/Setter同理,这里省略部分代码
    public List<RowItem> getRow() {
        return row;
    }

    public void setRow(List<RowItem> row) {
        this.row = row;
    }
}

// row数组里的元素类
public class RowItem {
    private String id;
    private String shortURL;
    private String title;
    private String text;
    private String img;
    private String price;

    // Getter和Setter方法
    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getShortURL() {
        return shortURL;
    }

    public void setShortURL(String shortURL) {
        this.shortURL = shortURL;
    }

    // 其他字段的Getter/Setter同理
}

如果用Kotlin会更简洁,直接用data class:

data class ApiResponse(val main: MainData)
data class MainData(
    val totalResults: String,
    val libelleCategory: String,
    val libelleSubCategory: String,
    val idCategory: String,
    val idSubCategory: String,
    val row: List<RowItem>
)
data class RowItem(
    val id: String,
    val shortURL: String,
    val title: String,
    val text: String,
    val img: String,
    val price: String
)

第三步:创建Retrofit接口

接下来定义一个接口,用来描述你的网络请求。假设这是一个GET请求,示例如下:

public interface ApiService {
    // 替换成你的实际接口路径
    @GET("your-endpoint-path")
    Call<ApiResponse> getMainData();
}

第四步:初始化Retrofit并发起请求

现在可以初始化Retrofit实例,然后调用接口方法发起请求了。通常我们会用异步请求(避免阻塞主线程):

// 初始化Retrofit
Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("https://your-base-url.com/") // 替换成你的基础URL
        .addConverterFactory(GsonConverterFactory.create()) // 添加Gson转换器
        .build();

// 创建接口实例
ApiService apiService = retrofit.create(ApiService.class);

// 发起异步请求
Call<ApiResponse> call = apiService.getMainData();
call.enqueue(new Callback<ApiResponse>() {
    @Override
    public void onResponse(Call<ApiResponse> call, Response<ApiResponse> response) {
        if (response.isSuccessful() && response.body() != null) {
            // 解析成功,获取数据
            MainData mainData = response.body().getMain();
            String totalResults = mainData.getTotalResults();
            List<RowItem> items = mainData.getRow();
            
            // 接下来就可以用这些数据做你想做的事了
            for (RowItem item : items) {
                String title = item.getTitle();
                String price = item.getPrice();
                // ...处理每个item的数据
            }
        } else {
            // 请求成功但响应有问题,比如HTTP状态码不是200-299
            // 可以打印response.errorBody()查看详情
        }
    }

    @Override
    public void onFailure(Call<ApiResponse> call, Throwable t) {
        // 请求失败,比如网络问题、URL错误等
        t.printStackTrace();
    }
});

几个关键注意点

  • 字段匹配:确保数据类的字段名和JSON里的键完全一致,或者用@SerializedName("json_key")来映射不同的命名(比如JSON里是total_results,你想在类里叫totalResults,就加@SerializedName("total_results"))。
  • Gson自动转换:Gson默认会帮你处理字符串转数字的情况(比如JSON里totalResults是"500",你可以在数据类里用Integer totalResults,Gson会自动转换)。
  • 空值处理:如果JSON里某些字段可能不存在,建议给数据类的字段加上@Nullable注解(Java),或者在Kotlin里用可空类型(比如val totalResults: String?)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 03:34:58