我正在尝试将请求序列化,然后再将其发送到Web服务调用的改进版。
当我正在序列化请求时,我需要传递json字符串以改造@Body paramenter中的调用,因此生成的json字符串将结果转换为带有“(在开头和结尾双引号)的json字符串。
“ {\” access_token \“:\” d80fa6bd6f78cc704104d61146c599bc94b82ca225349ee68762fc6c70d2dcf0 \“,\” fitness \“:[{\” _ id \“:\” 1d051bfe-df30-4fa0-808b-9d \“ \” _ activity“ \“ 877284d3-4f36-4ec0-a536-11563207dc4d \”,\“卡路里\”:600.0,\“距离\”:40.0,\“强度\”:\“ 100 \”,\“时间戳”:\“ 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 \”,\“卡路里\”:600.0,\“距离\”:40.0 ,\“ intensity \”:\“ 100 \”,\“ timestamp \”:\“ 2018-07-18T12:56:43 + 00:00 \”,\“ type \”:\“ Running \”,\ “ 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);
我正在尝试将请求序列化,然后再将其发送到Web服务调用的改进版。当我正在序列化请求时,我需要传递json字符串以在@Body paramenter中对电话进行改造,并应......>
使用对象消除了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..
}