Search code examples
jsonspringjacksonresteasy

Spring API should return JSON instead of escaped String


I have Spring endpoint which is supposed to return JSON so it can be collapsed/expanded via Chrome. Is there a way to tell Spring that string in message is actual Json representation, and no need to escape double quotes

Endpoint declaration:

@GET
@Path("/validate/{id}")
@Produces("application/json")
Response validate(@Context HttpServletRequest request, @PathParam("id") String id);    

Endpoint implementation:

public Response validate(HttpServletRequest request, String id) {
    try {
          return validatorService.validate(request, String id);
    } catch(Exception e) {
          throw new MyCustomException(e);
    }
}

Exception Handler:

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;
     }

}

Response:

   "json": "{  \"key\":  \"value\" }"

Expected response:

   "json": { "key":  "value" }

Solution:

 private JsonNode convertToJson(String json) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readTree(json);
        } catch (IOException e) {
            return NullNode.getInstance();
        }
    }

Solution

  • You are converting your object to string in json format. Spring just returns a string value in json parameter. If you want to return json formated object not string do not convert your object to string( json ). Convert your json to Object type and delete the line below.

    String json = buildJsonResponse(exception);
    

    If you want to return custom json in string parameter convert your all object to json not only its variable.

    You can just return string from your rest api with produces parameter like you added. produces = "application/json"