What's the best way to convert pojo to JSON in Spring What's the best way to convert pojo to JSON in Spring json json

What's the best way to convert pojo to JSON in Spring


Spring boot uses Jackson libraries to convert Java POJO Object to/from Json. These converters are created and used automatically for Rest services to convert POJO object returned by Rest method to Json (e.g. Rest service methods annotated with @ResponseBody). If Rest services are used then Spring creates POJO/Json converters automatically. If you want to make POJO/Json conversion in some different case you need com.fasterxml.jackson.databind.ObjectMapper.

Avoid creating ObjectMapper instance by operator new, reuse the ObjectMapper already available in Spring application context using dependency injection annotation @Autowired.Spring will automatically inject value to your objectMapper variable.

public class clA {    @Autowired    private ObjectMapper objectMapper;    public Optional<String> objToJson(MyObj obj) {            try {                String objJackson = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(obj));            } catch (JsonProcessingException e) {                log.debug("failed conversion: Pfra object to Json", e);            }        });}


If you don't want to use Spring MVC to convert object to JSON string, you could do it like this:

private JsonGenerator jsonGenerator = null;private ObjectMapper objectMapper = null;public void init(){  objectMapper = new ObjectMapper();  try{     jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(System.out, JsonEncoding.UTF8);     jsonGenerator.writeObject(bean);      objectMapper.writeValue(System.out, bean);  }catch (IOException e) {        e.printStackTrace();  }  jsonGenerator.flush();  jsonGenerator.close();}

You must declare the bean like this

public class AccountBean {    private int id;    private String name;    private String email;    private String address;    private Birthday birthday;    //getters, setters    @Override    public String toString() {        return this.name + "#" + this.id + "#" + this.address + "#" + this.birthday + "#" + this.email;    }}


import com.fasterxml.jackson.databind.ObjectMapper;import com.fasterxml.jackson.databind.SerializationFeature;public static String jsonToPojo(Object targetPojo) {    if(targetPojo == null)        return null;    ObjectMapper mapper = new ObjectMapper();    try {         mapper.enable(SerializationFeature.INDENT_OUTPUT);         return mapper.writeValueAsString(targetPojo);    } catch (IOException e) {        LOGGER.error("Error parsing string to json. Target pojo : {}", targetPojo.getClass().getName() );    }     return null;}