gson 改型请求正文正在@Body参数中添加双引号

o4hqfura  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(201)

I am trying to serialize the request before sending it to the retrofit for webservice calls.
as i am serializing the request , i need to pass json string to retrofit calls in @Body paramenter and due to that the generated json string results into following json string with the " (Double quotes in front and end ).
"{"access_token":"d80fa6bd6f78cc704104d61146c599bc94b82ca225349ee68762fc6c70d2dcf0","fitness":[{"_id":"1d051bfe-df30-4fa0-808b-9d7300a608ab","activity_id":"877284d3-4f36-4ec0-a536-11563207dc4d","calories":600.0,"distance":40.0,"intensity":"100","timestamp":"2018-07-18T12:56:43+00:00","type":"Running","utc_offset":"+05:30"},{"_id":"2004ff72-707d-489a-927e-4cdeed410095","activity_id":"5ed7c90f-805e-4763-aa62-7f8126c84f06","calories":600.0,"distance":40.0,"intensity":"100","timestamp":"2018-07-18T12:56:43+00:00","type":"Running","utc_offset":"+05:30"}]}"
as there are double quotes the third party api is unable to parse it successfully.
here is my reqeust serializer code

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;

    }
 }

code to call retrofit webservice

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);
smdnsysy

smdnsysy1#

使用对象消除了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 -> { } )

相关问题