Search code examples
jsonspringjacksonpojo

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


I have a requirement to convert a POJO to JSON string in a Spring project. I know Spring MVC provide a convenient way to return json in the controller by annotate @ResponseBody, I wonder how does Spring convert pojo to JSON internally? From the Spring MVC maven dependencies hierachy, I find jackson-databind and jackson-core library. While reading the Jackson tutorial, it says different library:

<dependencies>
  <dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>1.8.5</version>
  </dependency>
</dependencies>

And the convert code is similar as below:

ObjectMapper mapper = new ObjectMapper();
mapper.writeValue(new File("c:\\user.json"), user);

My questions are:

1: How does spring restful controller convert POJO to JSON? By using Jackson but different dependency library?

2: If I use above Jackson example to convert POJO to JSON, do I have to write the json to file? Is it possible to get the JSON string directly?

3: What's the best way to convert POJO to JSON in Spring project -- Without using @ResponseBody, since I want to convert POJO to JSON and save it to database, @ResponseBody is for restful service, not suitable for my case.

Thanks a lot for your answers in advance.


Solution

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