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

如何在Retrofit 2中处理同一接口返回的不同JSON响应类型

Got it, let's walk through exactly how to use Retrofit to map your API's JSON response to those POJO classes you generated with jsonschema2pojo. It's straightforward once you break it down into steps:

Step 1: Add Retrofit Dependencies to Your Project

First, you need to include Retrofit and its Gson converter (since jsonschema2pojo generates classes compatible with Gson by default) in your project. If you're using Gradle, add these lines to your module-level build.gradle (or build.gradle.kts for Kotlin):

dependencies {
    // Retrofit core library
    implementation 'com.squareup.retrofit2:retrofit:2.9.0'
    // Gson converter for JSON-to-POJO mapping
    implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
}

(Note: Swap in the latest version numbers if they're available.)

Step 2: Verify Your Generated POJOs

Double-check the classes you got from jsonschema2pojo:

  • You’ll have a root POJO class that matches the outermost structure of your API's JSON response—this is what Retrofit will map the entire response to.
  • Make sure all nested classes (for objects inside the JSON) are present, and that fields have the correct @SerializedName annotations (these tell Gson how to match JSON keys to your class fields).
Step 3: Create a Retrofit Instance

Next, set up a Retrofit instance with your API's base URL and the Gson converter. The base URL should be the part of your API address before the endpoint path:

Retrofit retrofit = new Retrofit.Builder()
    .baseUrl("https://test324y.highape.com/") // Important: This must end with a slash
    .addConverterFactory(GsonConverterFactory.create())
    .build();
Step 4: Define an API Service Interface

Create an interface to describe your API endpoint. This tells Retrofit what HTTP method to use, the endpoint path, and what parameters/response type to expect:

public interface HomepageApiService {
    // The endpoint path matches your API's path after the base URL
    @GET("api/get_homepage_data")
    // Replace HomepageData with the name of your generated root POJO class
    Call<HomepageData> getHomepageData(@Query("token") String token);
}
Step 5: Execute the Request & Access the Filled POJOs

Now you can use the service interface to make the API call and get your populated POJO. For Android, always use asynchronous calls (via enqueue) to avoid blocking the main thread:

// Create an instance of your API service
HomepageApiService apiService = retrofit.create(HomepageApiService.class);

// Make the call with your token
Call<HomepageData> call = apiService.getHomepageData("xyz123");

// Execute the call asynchronously
call.enqueue(new Callback<HomepageData>() {
    @Override
    public void onResponse(Call<HomepageData> call, Response<HomepageData> response) {
        if (response.isSuccessful() && response.body() != null) {
            // Success! The response body is your fully populated root POJO
            HomepageData homepageData = response.body();
            
            // Now you can access all nested objects/fields from homepageData
            // Example: homepageData.getFeaturedItems(), homepageData.getUserProfile(), etc.
        } else {
            // Handle HTTP errors (e.g., 404, 500)
            Log.e("RetrofitError", "Request failed: " + response.code());
        }
    }

    @Override
    public void onFailure(Call<HomepageData> call, Throwable t) {
        // Handle network failures or parsing errors
        Log.e("RetrofitFailure", "Error: " + t.getMessage());
        t.printStackTrace();
    }
});
Quick Troubleshooting Tips
  • If you get parsing errors: Check that your POJO fields match the JSON keys exactly (use @SerializedName if there's a mismatch, e.g., @SerializedName("user_name") String userName).
  • Ensure all nested classes are included in your project (jsonschema2pojo might generate them as inner classes or separate files—both work as long as they're accessible).
  • Double-check your base URL: It must end with a slash, and the endpoint path in your interface must not start with a slash.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 06:59:09