我已经实现了一个Restful Webservice,通过注释@Produces("application/json")
生成JSON作为我的响应
Am使用错误代码处理应用程序错误。所以我形成一个带有错误代码和错误消息的对象。因此,只要有应用程序异常,它将以XML格式生成。如何产生JSON格式的内容?
最佳答案
是的你可以。捕获异常并使用您的自定义异常类处理它,并通过将响应内容类型设置为application/json引发异常类
try{
InitialContext ctx = new InitialContext();
TestIntf intf = (TestIntf)ctx.lookup("java:comp/env/ejb/TestImpl");
}catch(NamingException namingException) {
CustomException lookupException = new CustomException("SYSJNDIE001", namingException.getMessage());
throw lookupException;
}
而且您的Exception类看起来像这样
public class CustomException extends Exception {
private static final long serialVersionUID = -5358934896070563181L;
public CustomException(String errorCode, String message) {
super(errorCode, message);
}
}
创建提供程序类Mapper的异常
@Provider
public class FaultResponseMapper implements ExceptionMapper<CustomException> {
@Context
private HttpHeaders headers;
@Override
public Response toResponse(CustomException customException) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR)
.entity(customException)
.type(MediaType.APPLICATION_JSON).build();
}
}
关于json - 如何在JSON响应中产生错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28500387/