问题 :
默认情况下,翻新使用GSON将HTTP正文与JSON相互转换。用@Body注释指定的对象将传递给GSON进行序列化,该序列化基本上将JAVA对象转换为JSON表示形式。此JSON表示形式将是HTTP请求正文。
JSONObject通过name将所有键值映射存储在成员变量中
namevaluePairs。这是JSONObject实现的摘录:
public class JSonObject { ... private final Map<String, Object> namevaluePairs; ...}当您将JSONObject传递给@Body批注时,将对这个JSONObject进行序列化,因此HTTP请求正文包含:{“ namevaluePairs”:“
actual JSON Object”}。
解:
将实际的JAVA对象传递给@Body批注,而不是其对应的JSONObject。GSON将负责将其转换为JSON表示形式。
例如
class HTTPRequestBody { String key1 = "value1"; String key2 = "value2"; ...}// GSON will serialize it as {"key1": "value1", "key2": "value2"}, // which will be become HTTP request body.public interface MyService { @Headers({"Content-type: application/json", "Accept: */*"}) @POST("/test") void postJson(@Body HTTPRequestBody body, Callback<Response> callback);}// UsageMyService myService = restAdapter.create(MyService.class);myService.postJson(new HTTPRequestBody(), callback);替代解决方案:
建议的解决方案之一是使用TypedInput:
public interface MyService { @POST("/test") void postRawJson(@Body TypedInput body, Callback<Response> callback);}String json = jsonRequest.toString();TypedInput in = new TypedByteArray("application/json", json.getBytes("UTF-8"));myService.postRawJson(in, callback);


