无法清除 retrifit2 响应上的异常"JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT bu



我发现了许多相关的问题,但我无法解决我的问题,因为我对改装不太熟悉。

RestServiceBuilder.getApiService().getAllProductByCatId(TOKEN, Constants.KEY_ROUTE_PRODUCTS_BY_CAT_ID,
Constants.LIST_VIEW_LIMIT, page, CATEGORY_ID).enqueue(new Callback<ProductListBaseModel>() {
@Override
public void onResponse(Call<ProductListBaseModel> call, Response<ProductListBaseModel> response) {
if (response.code() == 400 || response.code() == 500) {
ErrorPojoClass errorPojoClass = ErrorUtils.parseApiError(response);
CustomPopup.displayErrorPopup(a, errorPojoClass);
} else {
try {
if (response.body().getData().isEmpty()) {
pullToLoadView.setComplete();
isLoading = false;
if (page == 1) {
OnProductListResponse listResponse = (OnProductListResponse) a;
listResponse.onEmptyProductListFound(true); // produts not found
} else {
}
} else {
setupAdapterView(page, response);
OnProductListResponse listResponse = (OnProductListResponse) a;
listResponse.onEmptyProductListFound(false); // produts found
}
isSingleProduct = false;
} catch (Exception e) {
Log.e( "found",""+e);
}
}
}
@Override
public void onFailure(@NonNull Call<ProductListBaseModel> call, Throwable t) {
isLoading = false;
Log.e( "found",""+t);
}
});

以下是我如何创建改装对象

public static <S> S createService(Class<S> serviceClass) {
Gson gson = new GsonBuilder()
.setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ")
.setLenient()
.create();
HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
OkHttpClient client = new OkHttpClient.Builder()
.addInterceptor(interceptor).build();

Retrofit retrofit = new Retrofit.Builder()
.client(client)
.baseUrl(OPENCART_BASEURL)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();

return retrofit.create(serviceClass);
}

这是我的模型类,用于存储响应中的数据。

public class ProductListBaseModel {
@SerializedName("success")
@Expose
private Integer success;
@SerializedName("error")
@Expose
private List<Object> error = null;
@SerializedName("data")
@Expose
private List<ProductListDataModel> data = null;
public Integer getSuccess() {
return success;
}
public void setSuccess(Integer success) {
this.success = success;
}
public List<Object> getError() {
return error;
}
public void setError(List<Object> error) {
this.error = error;
}
public List<ProductListDataModel> getData() {
return data;
}
public void setData(List<ProductListDataModel> data) {
this.data = data;
}
private String unknown_error;
public ProductListBaseModel(int statusCode, String message) {
this.success = statusCode;
this.unknown_error = message;
}

}

我已经记录了流程,然后得到了的异常

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING

我检查了波斯曼的回复,发现这是一个有效的Json数据。我发现了许多与此相关的问题,但无法解决我的问题。

这是由于您定义的模型类用于获取字符串格式的数据,而来自API的数据为OBJECT格式。

确保为获取数据而定义的模型类与从API获取的数据格式完全相同。

最新更新