改造 2 RequestBody JsonArray

Retrofit 2 RequestBody JsonArray

如何在不引发运行时异常的情况下将 JSONArray 放入 RequestBody

@Multipart 
@POST("/call_method")
Call<MyResponse> callMethod(@Part("token")RequestBody token,@Part("params")RequestBody params);

我需要将 JSONArray 放入参数中。我目前在做什么:

callMethod(RequestBody.create(MediaType.parse("text/plain"), token),
           RequestBody.create(MediaType.parse("text/plain"), jsonArrayParams));

但是当我执行这个方法时,我会得到一个运行时异常:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line

非常有趣:请求已执行(通过 CharlesProxy 检查)但由于运行时异常我看不到结果。 我该如何修复这个错误?

执行没问题,你的问题在响应中,

Expected BEGIN_OBJECT but was BEGIN_ARRAY

当你声明接收一个对象时 Call<MyResponse> 而你正在接收一个数组

您需要更改回调中的类型,如下所示

Call<MyResponse[]> callMethod(@Part("token")RequestBody token,@Part("params")RequestBody params);

Call<List<MyResponse>> callMethod(@Part("token")RequestBody token,@Part("params")RequestBody params);