javajsonjacksonspring-data-jpagson

Best way to make JSON pretty in Java


I have list of objects returning like the below format (not pretty).

{"data":[{"id":1,"firstName":"Bill","lastName":"Johnson"}]

I would like it to show like this (pretty).

{
    "data":[{
        "id":1,"
        firstName":"Bill",
        "lastName":"Johnson"
        }]
}

This is my method signature, along with my call to the service to query the DB and the return that prints json to screen.

public @ResponseBody ResponseEntity<ResponseData<List<NameSearchDTO>>> getInfo(@PathVariable String code, @PathVariable String idType)

ResponseData<List<NameSearchDTO>> response = new ResponseData<>();

List<NameSearchDTO> results = officeService.getByCode(code, idType); 
if (!results.isEmpty()) {
            response.setData(results);
            response.setStatus(Enum.SUCCESS.getDescription());
            response.setMessage(Enum.STATUS_SUCCESS.getDescription());
return new ResponseEntity<>(response, HttpStatus.OK);
}

The ResponseData Class implements Serializable. Does this make it "true" JSON as I'm not using Jackson or any other JSON library?

How do I pass the response to the below ObjectMapper to make it pretty?

ObjectMapper jacksonMapper = new ObjectMapper();
jacksonMapper.configure(SerializationFeature.INDENT_OUTPUT, true);

Or do I need to create some sort of JSONHelper class?

ResponseData Class

public class ResponseData <E> implements Serializable{


    private E data;
    private String status;
    private String message;
    private boolean hasValidationError = false;

    public E getData() {
        return data;
    }

    public void setData(E data) {
        this.data = data;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public boolean getHasValidationError(){
        return hasValidationError;
    }

    public void setHasValidationError(boolean hasValidationError){
        this.hasValidationError = hasValidationError;
    }
}

Solution

  • I think the best way beautify the json string is as follows using Jackson:

    import com.fasterxml.jackson.databind.ObjectMapper;
    ObjectMapper objectMapper = new ObjectMapper();
    objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(yourObject)