我有 Spring 端点,它应该返回 JSON,因此它可以通过 Chrome 折叠/展开。有没有办法告诉 Spring 消息中的字符串是实际的 Json 表示,不需要转义双引号
端点声明:
@GET
@Path("/validate/{id}")
@Produces("application/json")
Response validate(@Context HttpServletRequest request, @PathParam("id") String id);
端点实现:
public Response validate(HttpServletRequest request, String id) {
try {
return validatorService.validate(request, String id);
} catch(Exception e) {
throw new MyCustomException(e);
}
}
异常处理程序:
public class ExceptionHandler implements ExceptionMapper {
@Override
public Response toResponse(MyCustomException exception) {
String json = buildJsonResponse(exception);
Message message = new Message(json);
return Response.status(ERROR_HTTP_STATUS_CODE).entity(response).build();
}
}
public class Message {
String json;
public Message(String json) {
this.json = json;
}
public String getJson() {
return json;
}
}
响应:
"json": "{ \"key\": \"value\" }"
预期响应:
"json": { "key": "value" }
解决方法:
private JsonNode convertToJson(String json) {
ObjectMapper mapper = new ObjectMapper();
try {
return mapper.readTree(json);
} catch (IOException e) {
return NullNode.getInstance();
}
}
最佳答案
你为什么不用 @JsonRawValue 注释你的 getter
public class Message {
String json;
public Message(String json) {
this.json = json;
}
@JsonRawValue
public String getJson() {
return json;
}
}
那个
关于json - Spring API 应该返回 JSON 而不是转义字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55972268/