Dropwizard - 以字符串作为实体的 jax-rs 响应返回预期 'u' 而不是 'e'
Dropwizard - jax-rs Response with string as entity is returning expected 'u' instead of 'e'
我的代码中有以下端点:
@GET
@UnitOfWork
@Timed
@Path("/create")
public Response register(@QueryParam("name") String name,
@QueryParam("password") String password) {
// Bcrypt encryption for password
String encr = enc.encrypt(password);
// Create a new user object to use with DAO.
User newUser = new User(name, encr);
// Save the user to the database and return a string which represents the ID.
String res = "newID : " + _userDAO.createUser(newUser);
// Return the string inside a response.
return Response.status(201).entity(res).build();
}
Bcrypt 有效,用户确实被添加到数据库中 - 我还在 "res" 字符串中得到了一个有效 ID。我认为这个错误要么与 res 字符串的格式有关,要么与我构建响应的方式有关 - 但是当我通过休息客户端调用它时,我不断得到以下结果:
Expected 'u' instead of 'e'
有时u和e字符会变,但错误的要点是一样的
此 class 被注释为生成 JSON - 也许与此有关?
感谢所有帮助
在你的行中
return Response.status(201).entity(res).build();
您将响应的实体设置为一个字符串(因为 "res" 是一个字符串)。
你的字符串是 "newID : <...>"。由于缺少 json 括号,您正在构建格式错误的 json 字符串。正确的是“{newID : <...>}”
但是您不应该自己构建 json 字符串。 Dropwizard 应该为您做这件事。
您需要将您的 "res" 放入一个对象中。像这样:
public class RegistrationResponse {
public int newID;
public RegistrationResponse(int newID) {
this.newID = newID;
}
}
@GET
@UnitOfWork
@Timed
@Path("/create")
public RegistrationResponse register(@QueryParam("name") String name,
@QueryParam("password") String password) {
String encr = enc.encrypt(password);
User newUser = new User(name, encr);
int newID = _userDAO.createUser(newUser);
return new RegistrationResponse(newID);
}
我的代码中有以下端点:
@GET
@UnitOfWork
@Timed
@Path("/create")
public Response register(@QueryParam("name") String name,
@QueryParam("password") String password) {
// Bcrypt encryption for password
String encr = enc.encrypt(password);
// Create a new user object to use with DAO.
User newUser = new User(name, encr);
// Save the user to the database and return a string which represents the ID.
String res = "newID : " + _userDAO.createUser(newUser);
// Return the string inside a response.
return Response.status(201).entity(res).build();
}
Bcrypt 有效,用户确实被添加到数据库中 - 我还在 "res" 字符串中得到了一个有效 ID。我认为这个错误要么与 res 字符串的格式有关,要么与我构建响应的方式有关 - 但是当我通过休息客户端调用它时,我不断得到以下结果:
Expected 'u' instead of 'e'
有时u和e字符会变,但错误的要点是一样的
此 class 被注释为生成 JSON - 也许与此有关?
感谢所有帮助
在你的行中
return Response.status(201).entity(res).build();
您将响应的实体设置为一个字符串(因为 "res" 是一个字符串)。 你的字符串是 "newID : <...>"。由于缺少 json 括号,您正在构建格式错误的 json 字符串。正确的是“{newID : <...>}”
但是您不应该自己构建 json 字符串。 Dropwizard 应该为您做这件事。
您需要将您的 "res" 放入一个对象中。像这样:
public class RegistrationResponse {
public int newID;
public RegistrationResponse(int newID) {
this.newID = newID;
}
}
@GET
@UnitOfWork
@Timed
@Path("/create")
public RegistrationResponse register(@QueryParam("name") String name,
@QueryParam("password") String password) {
String encr = enc.encrypt(password);
User newUser = new User(name, encr);
int newID = _userDAO.createUser(newUser);
return new RegistrationResponse(newID);
}