如何在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:
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.)
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
@SerializedNameannotations (these tell Gson how to match JSON keys to your class fields).
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();
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); }
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(); } });
- If you get parsing errors: Check that your POJO fields match the JSON keys exactly (use
@SerializedNameif 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

