当前位置: 首页 > 知识库问答 >
问题:

java.lang.IllegalStateException:应为BEGIN_OBJECT,但在第1行第1列路径$[DUPLICAT]处为字符串

养星汉
2023-03-14
public static WebService getRestService(String newApiBaseUrl, String accessToken)
    {
        OkHttpClient.Builder httpClient = new OkHttpClient.Builder();


        if (BuildConfig.DEBUG) {
            HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            httpClient.addInterceptor(logging);
        }


        Gson gson = new GsonBuilder()
                .setLenient()
                .create();

        restBuilder = new Retrofit.Builder()
                .baseUrl(newApiBaseUrl)
                .client(httpClient.build())
                .addConverterFactory(GsonConverterFactory.create(gson));

        if (accessToken != null) {
            AuthenticationInterceptor interceptor =
                    new AuthenticationInterceptor(accessToken);

            if (!httpClient.interceptors().contains(interceptor)) {
                httpClient.addInterceptor(interceptor);

                restBuilder.client(httpClient.build());
            }
        }

        retrofit = restBuilder.build();
        return retrofit.create(WebService.class);
    }
@Headers({
            Constants.ApiHeader.CONTENT_TYPE_JSON
    })

    @POST("POST_URL/{number}")
    Call<MyResponseModel> getActualProductLocation(@Header("access_token") String accessToken, @Path("number") String number, @Body List<MyRequestModel> body);
Response.status(200).entity("Response Success").build()

共有1个答案

邵繁
2023-03-14

因为后端不使用JSON格式的数据回复您,所以您必须使用自定义转换器来处理它。

这里有一个自定义转换器的例子,可以满足您的需要。

来自StringConverterFactory.java的片段

...
private static class StringConverter implements Converter<String> {
    private static final MediaType PLAIN_TEXT = MediaType.parse("text/plain; charset=UTF-8");

    @Override
    public String fromBody(ResponseBody body) throws IOException {
        return new String(body.bytes());
    }

    @Override
    public RequestBody toBody(String value) {
        return RequestBody.create(PLAIN_TEXT, convertToBytes(value));
    }

    private static byte[] convertToBytes(String string) {
        try {
            return string.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
    }
}
...
Retrofit retrofit = new Retrofit.Builder()
   ...
   .addConverterFactory(StringConverterFactory.create());
   ...
   .build();
 类似资料: