我使用Retrofit向我的服务器发送POST
请求:
@POST("/login")
void login( @Body User user ,Callback<User> callback);
我的user
对象只有email
和password
个字段。
检查日志,我可以看到我的参数是以这种格式发送的:
D/Retrofit﹕{"email":"example@test.com","password":"asdfasdf"}
我需要对我的参数做些什么呢?
{"user" : {"email":"example@test.com","password":"asdfasdf"} }
答案 0 :(得分:6)
编辑:使用自定义JsonSerializer
:
public class CustomGsonAdapter {
public static class UserAdapter implements JsonSerializer<User> {
public JsonElement serialize(User user, Type typeOfSrc,
JsonSerializationContext context) {
Gson gson = new Gson();
JsonElement je = gson.toJsonTree(user);
JsonObject jo = new JsonObject();
jo.add("user", je);
return jo;
}
}
}
然后,在您的API客户端构建器上:
public static RestApiClient buildApiService() {
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.LOWER_CASE_WITH_UNDERSCORES)
.registerTypeAdapter(User.class, new CustomGsonAdapter.UserAdapter())
.create();
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint(API_URL)
.setConverter(new GsonConverter(gson))
.build();
return restAdapter.create(MudamosApi.class);
}
答案 1 :(得分:1)
解决问题的最简单模式是创建一个RequestPOJO类,例如:
File User.java:
public class User{
public String email;
public String password;
}
文件LoginRequestPojo.java:
public class LoginRequestPojo{
public User user;
public LoginRequestPojo(User user){
this.user = user;
}
}
并且,在您的改装2请求中:
@POST("/login")
void login( @Body LoginRequestPojo requestPojo, Callback<User> callback);
最后,您的请求正文:
{"user":{"email":"someone@something.com","password":"123123"
}}