我有这个模型类,它存储来自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