Spring Boot REST: Consuming and Producing JSON

Learn to create Spring Boot REST services that accept the requests and produce the responses in JSON format. We will delve into various aspects, including serialization, deserialization, customization, and the integration of third-party libraries for handling JSON.

1. JSON Support in Spring Boot

Spring Boot provides integration for the following JSON mapping libraries:

  • Jackson (Default)
  • Gson

In Spring Boot, Jackson is the preferred and default library for JSON serialization and deserialization.

When a Java object needs to be sent as a JSON response, Jackson automatically converts it into a JSON representation. Similarly, when JSON data is received in a request, Spring Boot automatically converts it into the corresponding Java object.

@PostMapping
public Product createProduct(@RequestBody Product product) {

    // Process the received JSON data (e.g., save to the database)
    return productService.createProduct(product);
}

Note that we can still use other lightweight JSON libraries (e.g. Fastjson, JSON-B, Boon, Flexjson, LoganSquare or Moshi) when the requirements arise.

2. Using Jackson for JSON Requests and Responses

Spring Boot provides various ways to customize the default serialization and deserialization process. Let’s explore in detail.

2.1. Default Autoconfiguration

Spring boot, by default, includes Jackson dependency and is part of spring-boot-starter-json. Using JacksonAutoConfiguration class, spring boot automatically configures Jackson with the following behavior:

  • The ObjectMapper bean in case none is already configured.
  • The Jackson2ObjectMapperBuilder bean in case none is already configured.
  • Auto-registration for all Module beans with all ObjectMapper beans (including the defaulted ones).

2.2. Producing the JSON Response

Any Spring @RestController in a Spring Boot application should render JSON response by default as long as Jackson is on the classpath.

In the given example, EmployeeList will be serialized by Jackson and serve as a JSON representation to the client.

@GetMapping
public List<Employee> getAll() {

  List<Employee> list = employeeService.getAll();
  return list;
}

Similarly, for creating or updating, the client can send the JSON payload in the request body. In the given example, Employee the object will be populated with JSON request.

@PostMapping
public ResponseEntity<?> createOrUpdate(Employee employee) 
  throws RecordNotFoundException {

    Employee newEmployee = employeeService.save(employee);
    return ResponseEntity.created().body(newEmployee).build();
}

2.3. Customizing Jackson ObjectMapper

Spring boot auto-configures MappingJackson2HttpMessageConverter as one of the default converters to handle request and response body conversion.

We can customize the default conversion behavior using either property files or custom bean definitions.

2.3.1. Property Configuration

Use the relevant properties to configure the desired behavior of ObjectMapper bean.

spring.jackson.date-format= # For instance, `yyyy-MM-dd HH:mm:ss`.
spring.jackson.default-property-inclusion= # Controls the inclusion of properties during serialization.
spring.jackson.deserialization.*= # Jackson on/off features for deserialization.
spring.jackson.generator.*= # Jackson on/off features for generators.
spring.jackson.joda-date-time-format= # Joda date time format string.
spring.jackson.locale= # Locale used for formatting.
spring.jackson.mapper.*= # Jackson general purpose on/off features.
spring.jackson.parser.*= # Jackson on/off features for parsers.
spring.jackson.property-naming-strategy= # PropertyNamingStrategy.
spring.jackson.serialization.*= # Jackson on/off features for serialization.
spring.jackson.time-zone= #  Time zone
spring.jackson.visibility.*= # To limit which methods (and fields) are auto-detected.

2.3.2. Java Configuration

Use anyone of the below bean configurations to override JSON behavior in spring boot.

@Configuration
public class WebConfig {

  @Bean
  public Jackson2ObjectMapperBuilderCustomizer jackson2ObjectMapperBuilderCustomizer() {
    return builder -> {

      // human readable
      builder.indentOutput(true);

      // exclude null values
      builder.serializationInclusion(JsonInclude.Include.NON_NULL);

      // all lowercase with under score between words
      builder.propertyNamingStrategy(PropertyNamingStrategy.SNAKE_CASE);
    };
  }
}

3. Using Gson with JSON Serialization/Deserialization

Spring Boot allows you to integrate with third-party JSON libraries if needed. For example, if you prefer Gson over Jackson, you can exclude Jackson and include Gson in your project:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-json</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
</dependency>

Spring boot detects the presence of Gson.class and uses GsonAutoConfiguration for configuring the Gson instance.

By default, Spring Boot will try to auto-configure a JSON mapper based on the libraries present in the classpath. If only one supported mapper is available, Spring Boot will use it as the default. If multiple mappers are present,we need to specify the default mapper explicitly.

For example, to make Gson the preferred JSON mapper, use the ‘spring.mvc.converters.preferred-json-mapper‘ property in application.properties file.

spring.mvc.converters.preferred-json-mapper=gson

See Also: Gson with Spring Boot

We can customize the various aspects of serialization and deserialization using Gson using the following properties:

spring.gson.date-format= # Format to use when serializing Date objects.
spring.gson.disable-html-escaping= # Whether to disable the escaping of HTML characters such as '&lt;', '&gt;', etc.
spring.gson.disable-inner-class-serialization= # Whether to exclude inner classes during serialization.
spring.gson.enable-complex-map-key-serialization= # Whether to enable serialization of complex map keys (i.e. non-primitives).
spring.gson.exclude-fields-without-expose-annotation= # Whether to exclude all fields from consideration for serialization or deserialization that do not have the &quot;Expose&quot; annotation.
spring.gson.field-naming-policy= # Naming policy that should be applied to an object's field during serialization and deserialization.
spring.gson.generate-non-executable-json= # Whether to generate non executable JSON by prefixing the output with some special text.
spring.gson.lenient= # Whether to be lenient about parsing JSON that doesn't conform to RFC 4627.
spring.gson.long-serialization-policy= # Serialization policy for Long and long types.
spring.gson.pretty-printing= # Whether to output serialized JSON that fits in a page for pretty printing.
spring.gson.serialize-nulls= # Whether to serialize null fields.

4. Conclusion

In Spring Boot, Jackson is the default JSON mapper library used. Also, note that Spring Boot provides the flexibility in choosing a JSON library,

In most cases, it might be more straightforward to rely on the default configuration. If you have specific requirements or preferences, you can explicitly configure the preferred JSON mapper using the property mentioned above.

Drop me your questions related to producing and consuming JSON in Spring Boot REST APIs.

Happy Learning !!

Comments

Subscribe
Notify of
guest
2 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode