Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
        }
    }
like image 313
yu.pitomets Avatar asked Jun 28 '26 15:06

yu.pitomets


1 Answers

Why don't you annotate your getter with @JsonRawValue

public class Message {
    String json;

    public Message(String json) {
        this.json = json;
    }

    @JsonRawValue
    public String getJson() {
       return json;
    }

}

That

like image 171
sparkyspider Avatar answered Jul 01 '26 04:07

sparkyspider