Retrofit2 POST请求成功但响应数据全为null问题求助
Hey there, I’ve run into this exact frustrating issue a few times before—when the server says the request worked but you get nothing but nulls back in the response. Let’s break down the most common culprits and how to fix them step by step:
1. Double-Check JSON ↔ Data Model Field Matching
This is hands down the #1 cause of null fields. Your data model class needs to align perfectly with the JSON structure the server returns.
Example Scenario:
Suppose the server returns this JSON:
{
"user_id": 456,
"full_name": "Boris El Gareh",
"user_email": "boris@example.com"
}
Common Mistakes to Fix:
- Missing
@SerializedNameannotations: If your model uses camelCase (likeuserIdinstead ofuser_id), Gson won’t map them automatically unless you explicitly link the JSON key to your field:public class UserResponse { @SerializedName("user_id") // Critical for matching the JSON key private int userId; @SerializedName("full_name") private String fullName; @SerializedName("user_email") private String userEmail; // Add getters/setters OR make fields public for Gson to access } - Field visibility issues: Gson needs access to your model’s fields. Either make fields
public, add proper getters/setters, or if you use@Expose, ensure your Gson builder enables it (e.g.,new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create()). - Mismatched data types: If the JSON returns a string for
user_idbut your model usesint, Gson will fail silently and set the field to null (or 0 for primitives).
2. Verify Retrofit & Converter Configuration
Retrofit relies on converters (like Gson) to parse JSON into your model. A misconfigured setup will cause silent parsing failures, even with a successful status code.
- Don’t skip the Gson converter: Without this, Retrofit can’t parse JSON—you’ll either get a raw
ResponseBodyor null fields:Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://your-api-url.com/") .addConverterFactory(GsonConverterFactory.create()) // This line is non-negotiable! .build(); - Check custom Gson settings: If you’re using a custom
Gsoninstance, make sure it’s not breaking parsing:- Avoid
setFieldNamingPolicyunless it matches your JSON’s naming convention (e.g.,LOWER_CASE_WITH_UNDERSCORESfor snake_case JSON). - Don’t enable
serializeNullsunless you intend to send null values—this doesn’t break parsing, but it’s a common misconfiguration that can cause confusion.
- Avoid
3. Validate Your API Service Interface
Small mistakes here can lead to unexpected parsing behavior:
- Match the response type to your model: Your interface method should return
Call<YourResponseModel>, notCall<ResponseBody>or the wrong generic type:public interface ApiService { @POST("users/create") Call<UserResponse> submitUser(@Body UserRequest userRequest); // Correct // Wrong: Call<ResponseBody> or using your request model for the response } - Use the right request annotation: For JSON payloads, use
@Body—don’t mix it up with@Fieldor@FormUrlEncodedunless you’re sending form data instead of JSON.
4. Debug the Raw Request/Response
You can’t fix what you can’t see. Add OkHttp’s logging interceptor to view the exact JSON response from the server—this will tell you if the issue is on the client (parsing) or server (returning nulls).
Add the Logging Interceptor:
// First add the dependency if missing: implementation 'com.squareup.okhttp3:logging-interceptor:4.12.0' HttpLoggingInterceptor loggingInterceptor = new HttpLoggingInterceptor(); loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY); // Logs full request/response details OkHttpClient okHttpClient = new OkHttpClient.Builder() .addInterceptor(loggingInterceptor) .build(); // Use this client in your Retrofit setup Retrofit retrofit = new Retrofit.Builder() .baseUrl("https://your-api-url.com/") .client(okHttpClient) .addConverterFactory(GsonConverterFactory.create()) .build();
Check your logcat for the Response body section. If the server is actually returning all null fields, the issue is on the backend. If the JSON has valid values but your model isn’t parsing them, go back to step 1.
5. Check Server-Side Logic
Sometimes the server returns a 200 OK but fails to populate the response data correctly (e.g., a bug in their database query or response serialization). The logging interceptor will confirm this—if the raw response JSON has nulls, you’ll need to follow up with the backend team.
内容的提问来源于stack exchange,提问作者Boris El Gareh

