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

Retrofit返回200 OK与正确JSON,但Parcelable对象为null求助

Troubleshooting Null Parcelable (Solicitacao) with Retrofit 2.0.0 & OkHttp 3.2.0

Hey there! It’s super frustrating when your Retrofit request returns a 200 OK with the exact JSON you expect, but your mapped Solicitacao (Parcelable) object ends up null. Let’s walk through the most common fixes and checks to get this sorted:

1. Double-Check Your Parcelable Implementation

Parcelable is picky about how you handle fields—even a small mistake here can break object reconstruction:

  • Make sure every field in Solicitacao is written to the Parcel in writeToParcel() and read back in the CREATOR’s createFromParcel() method. Don’t miss nested objects (if any) — they need to be written with parcel.writeParcelable() and read with parcel.readParcelable().
  • Verify field names match your JSON keys, or use @SerializedName annotations to map mismatched names. For example, if your JSON has solicitacao_id but your model uses solicitacaoId, add @SerializedName("solicitacao_id") private String solicitacaoId; to bridge the gap.

2. Confirm Retrofit’s Converter Factory is Configured

Retrofit 2 doesn’t include a JSON converter by default—if you forgot to add it, it can’t parse JSON into your model:

  • Ensure your Retrofit instance includes GsonConverterFactory (or your preferred converter) like this:
    Retrofit retrofit = new Retrofit.Builder()
        .baseUrl("YOUR_BASE_URL")
        .addConverterFactory(GsonConverterFactory.create()) // This is critical!
        .client(new OkHttpClient())
        .build();
    
  • If you’re using a custom Gson instance, double-check it isn’t ignoring fields or using incorrect serialization rules (like excluding fields without @Expose when you didn’t mean to).

3. Match Your API Interface Return Type to JSON Structure

  • If your JSON is a single Solicitacao object, your API method should return Call<Solicitacao>. If the JSON is wrapped in an outer object (e.g., {"data": {...}}), you’ll need a wrapper model:
    public class ApiResponse {
        @SerializedName("data")
        private Solicitacao solicitacao;
    
        // Getters/setters
    }
    
    Then your interface returns Call<ApiResponse>, and you extract response.body().getSolicitacao() to get your object.
  • Avoid returning Call<ResponseBody> unless you plan to manually parse the JSON—directly assigning a ResponseBody to a Solicitacao will result in null.

4. Dig Into the Exact Error Logs

You mentioned there’s an error—those logs are gold for pinpointing the issue!

  • In your Retrofit callback’s onFailure() method, log the full throwable:
    @Override
    public void onFailure(Call<Solicitacao> call, Throwable t) {
        Log.e("RetrofitError", "Failed to parse response", t);
    }
    
  • If onResponse() is called but response.body() is null, log the error body content:
    @Override
    public void onResponse(Call<Solicitacao> call, Response<Solicitacao> response) {
        if (response.isSuccessful()) {
            Solicitacao sol = response.body();
            if (sol == null) {
                try {
                    Log.e("NullObject", "Error body: " + response.errorBody().string());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    
    Common errors here include mismatched JSON types (e.g., expecting an object but getting an array) or missing required fields.

5. Test Parcelable in Isolation

Rule out Retrofit entirely by testing your Parcelable implementation alone:

// Create a test Solicitacao with known data
Solicitacao testSol = new Solicitacao("123", "Test Request");
// Write to Parcel
Parcel parcel = Parcel.obtain();
testSol.writeToParcel(parcel, 0);
// Reset position and read back
parcel.setDataPosition(0);
Solicitacao restoredSol = Solicitacao.CREATOR.createFromParcel(parcel);
// Compare fields to ensure they match
if (!testSol.getId().equals(restoredSol.getId())) {
    Log.e("ParcelableTest", "ID didn't survive serialization!");
}

If this test fails, the problem is 100% in your Parcelable code, not Retrofit.

6. Check for Dependency Conflicts

Retrofit 2.0.0 and OkHttp 3.2.0 are compatible, but conflicting library versions can cause unexpected behavior:

  • For Android projects, run ./gradlew dependencies to view your dependency tree. Look for multiple versions of Gson, OkHttp, or Retrofit—exclude older versions if needed.

If you can share your error logs, Solicitacao model code, Retrofit instance setup, and API interface definition, we can zero in on the exact issue even faster!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 08:44:03