Jax-RS响应生成应用程序/json:如何包装简单字符串?
以我的休息服务为例:Jax-RS响应生成应用程序/json:如何包装简单字符串?,json,jax-rs,Json,Jax Rs,以我的休息服务为例: @POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public Response authenticateUser(CredentialsDTO credentialsDTO) { try { authService.login(credentialsDTO.getUsername(), credentialsDTO.getPasswo
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response authenticateUser(CredentialsDTO credentialsDTO) {
try {
authService.login(credentialsDTO.getUsername(), credentialsDTO.getPassword());
} catch (WrongCredentialsException e) {
return Response.status(Status.UNAUTHORIZED).entity("WrongCredentialsException").build();
} catch (AccountLockedException e) {
return Response.status(Status.UNAUTHORIZED).entity("AccountLockedException").build();
}
String token = issueToken(credentialsDTO.getUsername());
return Response.ok().header(AUTHORIZATION, "Bearer " + token).build();
}
尽管我将application/json声明为内容类型,但在实体中返回字符串(例如“AccountLockedException”)可以吗?
我是否必须在将错误消息发回之前将其包装在Json对象中
当我试图将响应解析为Json时,我在客户端遇到了这个问题,但当出现错误时,只有文本返回。您肯定应该用Json包装字符串。 在这种情况下,代码可能是这样的:
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response authenticateUser(CredentialsDTO credentialsDTO) {
try {
authService.login(credentialsDTO.getUsername(), credentialsDTO.getPassword());
} catch (WrongCredentialsException e) {
return Response.status(Status.UNAUTHORIZED)
.entity(new JSONObject().put("message", "WrongCredentialsException").toString())
.build();
} catch (AccountLockedException e) {
return Response.status(Status.UNAUTHORIZED)
.entity(new JSONObject().put("message", "AccountLockedException").toString())
.build();
}
String token = issueToken(credentialsDTO.getUsername());
return Response.ok().header(AUTHORIZATION, "Bearer " + token).build();
}
或者您甚至可以为这些异常创建一个单独的类,并使用默认的JSON serialiser库序列化它们。使用.entity(“\”“+”错误凭证异常“+”)