2016-11-27 102 views
1

我有這個模型類,它存儲來自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對象默認爲nullvalue場?

編輯:請注意,我用這與改造,所以它的工作原理是這樣的。

// 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

+0

您的Retrofit API接口並不代表實際的響應類型(您等待列表並獲得一個對象) – EpicPandaForce

+0

@EpicPandaForce對不起,我只是使用了一個SampleClass來顯示我的問題的要點。我調整了它。 – Isaiah

回答

0

我試過下面的代碼,它似乎工作。

String jsonString = "{ \n" + 
      " \"id\":1 \n" + 
      "}"; 

    Gson gson = new Gson(); 
    SampleClass sampleClass = gson.fromJson(jsonString, SampleClass.class); 
+0

請參閱我的編輯。 – Isaiah

+0

Retrofit在引擎蓋下使用了gson(或者至少在使用Retrofit2時,如果在創建'Retrofit'實例時包含以下內容)。你是否能夠驗證你回來的原始json字符串是否如你所期望的那樣(並且在gson代碼片段上面運行)? '.addConverterFactory(GsonConverterFactory.create())' –

0
Gson gson = new GsonBuilder().serializeNulls().create(); 
Retrofit retrofit = .... 
.addConverterFactory(GsonConverterFactory.create(gson)); 

嘗試上面的同時創造改裝實例。它應該工作。

相關問題