首页 > 解决方案 > 无法将 retrifit2 响应中的异常清除为“JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING”

问题描述

我发现了许多相关的问题,但由于我对改造不太熟悉,所以我无法弄清楚我的问题。

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

我检查了 posman 中的响应,发现它是有效的 Json 数据。我发现了很多与此相关的问题,但无法解决我的问题。

标签: androidjsonretrofit2gson

解决方案


这是因为您定义的Model 类以 String 格式获取数据,而来自API的数据采用 OBJECT 格式。

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


推荐阅读