我有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();
}
}
答案 0 :(得分:2)
为什么不使用@JsonRawValue注释您的吸气剂
public class Message {
String json;
public Message(String json) {
this.json = json;
}
@JsonRawValue
public String getJson() {
return json;
}
}
那个
答案 1 :(得分:1)
您正在将对象转换为json格式的字符串。 Spring只是在json参数中返回一个字符串值。如果要返回json格式的对象而不是字符串,请不要将您的对象转换为string(json)。将您的json转换为Object
类型,然后删除下面的行。
String json = buildJsonResponse(exception);
如果要在字符串参数中返回自定义json,则将所有对象(不仅是变量)转换为json。
您可以从rest api返回带有产生的参数(如您添加的参数)的字符串。
produces = "application/json"