我有這個模型類,它存儲來自API調用的JSON對象和Retrofit。如何讓我的Retrofit模型類處理NULL屬性?
// Java
public class SampleClass extends RealmObject {
@SerializedName("id")
@Expose
private Integer id;
@SerializedName("value")
@Expose
private List<String> value;
}
// Json
{
"id":1,
"value":["one", "two"]
}
有些情況下JSON對象不會有values
,並且會出現這樣的情況。
{
"id":2,
"value":null
}
發生這種情況時,我得到了這個異常。
com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was NULL
我該如何處理這使得對於Java對象默認爲null
的value
場?
編輯:請注意,我用這與改造,所以它的工作原理是這樣的。
// Call to API
Call<SampleClass> call = apiService.getSampleClass();
call.enqueue(new Callback<SampleClass>() {
@Override
public void onResponse(Call<SampleClass> call, Response<SampleClass> response) {
// API Call was successful
}
@Override
public void onFailure(Call<Login> call, Throwable t) {
// Logging t.toString() shows the error above.
}
});
如果字段爲NULL,則調用總是落在onFailure
。
您的Retrofit API接口並不代表實際的響應類型(您等待列表並獲得一個對象) – EpicPandaForce
@EpicPandaForce對不起,我只是使用了一個SampleClass來顯示我的問題的要點。我調整了它。 – Isaiah