Does Spring have Jackson built in – If so how to parse JSON

Does Spring have Jackson built in – If so how to parse JSON

If you want to create a JSON response endpoint , all you need to do is create a rest endpoint that returns json. Springboot automatically configures jackson message converters for rest endpoints if it finds jackson as dependency or classpath.So all you need to enable a rest endpoint to return a json response is to have the jackson as dependency and springboot will take care of the rest through autoconfiguration.

By default spring or springboot configures the following message converters during startup:

ByteArrayHttpMessageConverter – converts byte arrays
StringHttpMessageConverter – converts Strings
ResourceHttpMessageConverter – converts org.springframework.core.io.Resource for any type of octet stream
SourceHttpMessageConverter – converts javax.xml.transform.Source
FormHttpMessageConverter – converts form data to/from a MultiValueMap<String, String>.
Jaxb2RootElementHttpMessageConverter – converts Java objects to/from XML
MappingJackson2HttpMessageConverter – converts JSON
MappingJacksonHttpMessageConverter – converts JSON
AtomFeedHttpMessageConverter – converts Atom feeds 
RssChannelHttpMessageConverter – converts RSS feeds

Dependencies that you may need to add :

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.9.8</version>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>

If you use Spring Boot, the jackson-databind dependency comes in the spring-boot-starter-json module (which also is included in other spring boot started moduled, like spring-boot-starter-web).

If you specify the starter module in your dependencies, you will be able to write read/write json program with the jackson version which comes with Spring. The good practice to specify this dependency explicitly since the functionality might change with Spring update.

The code example with Spring Boot:

@Bean
public CommandLineRunner commandLineRunner(ApplicationContext applicationContext) {
    return args -> {
        String john = objectMapper().writeValueAsString(new User(John, 43));

        System.out.println(john);
    };
}

@Bean
public ObjectMapper objectMapper() {
    return new ObjectMapper();
}

Update:
In Spring 5.1.* org.springframework.spring-web dependency, the Jackson is also provided and can be used as in the example above.

Does Spring have Jackson built in – If so how to parse JSON

You can simply inject ObjectMapper which already defined in Spring via @Autowired or constructor in the configuration. For example:

@Configuration
public class SomeConfiguration {

@Bean
public SomeService someService(ObjectMapper objectMapper) {
  return new SomeService(objectMapper);
}}

Leave a Reply

Your email address will not be published. Required fields are marked *