改装请求主体在@Body参数中添加双引号

时间:2018-07-20 06:10:25

标签: android json gson retrofit2

我正在尝试序列化请求,然后再将其发送到Web服务调用的改进版本。

当我正在序列化请求时,我需要传递json字符串以改造@Body paramenter中的调用,因此    生成的json字符串将结果转换为以下带有“(在开头和结尾双引号)的json字符串。

  

“ {\” access_token \“:\” d80fa6bd6f78cc704104d61146c599bc94b82ca225349ee68762fc6c70d2dcf0 \“,\” fitness \“:[{\” _ id \“:\” 1d051bfe-df30-4fa0-808b \ id \“ id”“ activity” :\“ 877284d3-4f36-4ec0-a536-11563207dc4d \”,\“卡路里\”:600.0,\“距离\”:40.0,\“强度\”:\“ 100 \”,\“时间戳”:\ “ 2018-07-18T12:56:43 + 00:00 \”,\“类型\”:\“运行\”,\“ utc_offset \”:\“ + 05:30 \”},{\“ _ id \ “:\” 2004ff72-707d-489a-927e-4cdeed410095 \“,\” activity_id \“:\” 5ed7c90f-805e-4763-aa62-7f8126c84f06 \“,\”卡路里“:600.0,\”距离\“: 40.0,\“强度\”:\“ 100 \”,\“时间戳\”:\“ 2018-07-18T12:56:43 + 00:00 \”,\“类型\”:\“正在运行\”, \“ utc_offset \”:\“ + 05:30 \”}]}“

因为有双引号,所以第三方api无法成功解析它。

这是我的需求序列化代码

 public class RequestSerializer implements JsonSerializer<Request<?>> {

    @Override
    public JsonElement serialize(Request<?> request, Type typeOfSrc, JsonSerializationContext context) {

        JsonObject jsonObject =  new GsonBuilder().create().toJsonTree(request,Request.class).getAsJsonObject();
        JsonElement requestList = jsonObject.get("requestList");
        jsonObject.remove("requestList");
        jsonObject.add("fitness",requestList);
        return jsonObject;

    }
 }

代码以调用改造Web服务

    GsonBuilder builder = new GsonBuilder();
    builder.excludeFieldsWithoutExposeAnnotation();
    builder.registerTypeAdapter(Request.class, new RequestSerializer());
    Gson gson = builder.create();

    String data = gson.toJson(request);

    Flowable<Response> fitnessFlowable = new WebRequest().getRemoteClient().create(FitnessApi.class).postFitnessData("5b238abb4d3590001d9b94a8",data);

1 个答案:

答案 0 :(得分:0)

使用对象消除了POST @Body中的字符串引用请求, 示例作为我的工作代码:

class Data{
    @SerializedName("access_token")
    @Expose
    private String access_token;

    public String getAccess_token() {
        return access_token;
    }

    public void setAccess_token(String access_token) {
        this.access_token = access_token;
    }

    // Other field defined here
}

@Keep
class Result{
    @SerializedName("rc") int rc;
}

@Keep
interface APIFitness{
    @Headers("Content-Type: application/json")
    @POST("api/save/")
    Observable<Result> Save(@Body Data data);

    //More methods..
}

使用

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl("url")
            .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    APIFitness service = retrofit.create(APIFitness.class);
    Data data = new Data();
    authCode.setAccess_token(token);

    service.Save(data)
           .subscribeOn(Schedulers.io())
           .observeOn(Schedulers.newThread())
           .subscribe( data -> { } )