Retrofit返回200 OK与正确JSON,但Parcelable对象为null求助
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
Solicitacaois written to the Parcel inwriteToParcel()and read back in the CREATOR’screateFromParcel()method. Don’t miss nested objects (if any) — they need to be written withparcel.writeParcelable()and read withparcel.readParcelable(). - Verify field names match your JSON keys, or use
@SerializedNameannotations to map mismatched names. For example, if your JSON hassolicitacao_idbut your model usessolicitacaoId, 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
@Exposewhen you didn’t mean to).
3. Match Your API Interface Return Type to JSON Structure
- If your JSON is a single
Solicitacaoobject, your API method should returnCall<Solicitacao>. If the JSON is wrapped in an outer object (e.g.,{"data": {...}}), you’ll need a wrapper model:
Then your interface returnspublic class ApiResponse { @SerializedName("data") private Solicitacao solicitacao; // Getters/setters }Call<ApiResponse>, and you extractresponse.body().getSolicitacao()to get your object. - Avoid returning
Call<ResponseBody>unless you plan to manually parse the JSON—directly assigning a ResponseBody to aSolicitacaowill 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 butresponse.body()is null, log the error body content:
Common errors here include mismatched JSON types (e.g., expecting an object but getting an array) or missing required fields.@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(); } } } }
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 dependenciesto 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

