Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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;
    }
}
like image 263
Angular_Newbie Avatar asked Mar 13 '26 03:03

Angular_Newbie


2 Answers

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)
like image 105
Rakesh Avatar answered Mar 14 '26 17:03

Rakesh


You can define

  • a MappingJacksonHttpMessageConverter (no need for Spring Boot)
  • a Jackson2ObjectMapperBuilder Bean
  • a simple ObjectMapper Bean annotated with @Primary
  • a configuration property (Spring Boot - skip to this one for the simplest).

For the first solution you need to implement the WebMvcConfigurer interface
(skip this one if you're on Spring Boot)

@Configuration
class CustomWebMvcConfigurer implements WebMvcConfigurer {
    @Override
    public void configureMessageConverters(final List<HttpMessageConverter<?>> converters) {
        final ObjectMapper mapper =
                new Jackson2ObjectMapperBuilder()
                        .indentOutput(true)
                        .build();

        // Or build ObjectMapper without the Spring builder, it's the same thing
        converters.add(new MappingJackson2HttpMessageConverter(mapper));
    }
}

The key is this line

indentOutput(true)

Which actually manipulates the underlying ObjectMapper configuration

public Jackson2ObjectMapperBuilder indentOutput(boolean indentOutput) {
    this.features.put(SerializationFeature.INDENT_OUTPUT, indentOutput);
    return this;
}

The second one is a bit simpler

@Bean
Jackson2ObjectMapperBuilder jackson() {
   return new Jackson2ObjectMapperBuilder().indentOutput(true);
}

The third one is even simpler, just

@Bean
@Primary
ObjectMapper objectMapper() {
   final ObjectMapper mapper = new ObjectMapper();
   mapper.enable(SerializationFeature.INDENT_OUTPUT);  
   return mapper;
}

A fourth way consists only on using the configuration property

spring.jackson.serialization.indent_output=true
like image 38
LppEdd Avatar answered Mar 14 '26 15:03

LppEdd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!