The Wayback Machine - https://web.archive.org/web/20241001032411/https://www.geeksforgeeks.org/json-using-jackson-in-rest-api-implementation-with-spring-boot/
Open In App

JSON using Jackson in REST API Implementation with Spring Boot

Last Updated : 27 Nov, 2020
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Whenever we are implementing a REST API with Spring (Spring Boot), we would have come across the requirement to exclude NULLs in the JSON Response of the API. Also, there might be a requirement to externalize turning ON/OFF this feature: Exclude NULLS in the JSON Response, thereby allowing the consumer of the API to customize as per the need.

In this article, we summarize the approach that used to implement the Externalization of ON/OFF the above-mentioned feature using Jackson – A java-based library to serialize or map java objects to JSON and vice versa.

Unsuccessful Approaches :

Initially, we tried with the Spring Boot’s readily available approaches, which were not successful, such as:

  • Having spring.jackson.default-property-inclusion property in application.properties. This property takes values such as: always/non_null/non_absent/non_default/non_empty.
  • Extending WebMvcConfigurationSupport class and customize the Spring Boot configuration, see below.

Java




@Configuration
class WebMvcConfiguration extends WebMvcConfiguration{
    @Override
    protected void extendsMessageConverters
      (List<HttpMessageConverter<?>> converters)
    {
        for(HttpMessageConverter<?> converter: converters)
        {
            if(converter instnceof MappingJackson2HttpMessageConverter)
            {
                ObjectMapper mapper = 
                  ((MappingJackson2HttpMessageConverter)converter)
                  .getObjectMapper();
                mapper.setSerializationInclusion(Include.NON_NULL);
                }
            }
        }


Now, Creating an instance of org.springframework.http.converter.json.Jackson2ObjectMapperBuilderCustomizer, Below the given code is for your reference.

Java




@Bean
Public Jackson2ObjectMapperBuilderCustomizer customJackson(){
    return new Jackson2ObjectMapperBuilderCustomizer(){
    @Override
    public void customize(Jackson2ObjectMapperBuilder builder){
        builder.serializationInclusion(Include.NON_NULL);
        builder.failonUnknownProperties(false);
        }
    };
}


Successful Approach:

Create a JSON Response Object, if not created. This is the object which while serializing to JSON you want to ‘Exclude/Include Null fields’ feature based on the property in application.properties. You can see below the Response object for your reference.

Java




public class RegistrationResponse{
  
    @JsonProperty("success")
    private Boolean success = null;
      
    @JsonProperty("message")
    private String message = null;
      
    @JsonProperty("data")
    private String data = null;
      
    @JsonProperty("error_code")
    private Integer errorCode = null;
      
    public RegistrationResponse success(Boolean success){
        this.success = success;
        return this;
        }
          
        @NotNull
        public Boolean isSuccess(){
            return success;
            }
        public void setSuccess(Boolean success){
            this.success = success;
        }
          
        public RegistrationResponse message(String message){
            this.message = message;
            return this;
            }
              
        @NotNull
        public String getMessage(){
            return message;
        }
          
        public void setMessage(String message){
            this.message = message;
        }


Create a property by the name ‘config.response.json.format.exclude_null’ which can take values as ‘true’ or ‘false’. The value ‘true’ means to exclude null fields in the JSON Response & the value ‘false’ means to not exclude null fields. Also, bind this property to a class-level property so that the value can be read, Below given code is for your reference.

config.response.json.format.exclude_null = false
@Value("${config.response.json.format.exclude_null}")
private boolean toExcludeNull;

Implement the actual logic to exclude nulls based on the global property value by – Creating an instance of com.fasterxml.jackson.databind.ObjectMapper.

  • Setting SerializationInclusion property of the created mapper to Include.NON_NULL if the global property value is true, otherwise set to Include.ALWAYS.
  • Serialize the Response object to a String using the mapper & return the String. Make sure to handle JsonProcessingException.

Let’s see below for the actual code snippet to be added while constructing the JSON Response as part of the API implementation.

Java




RegistrationResponse regResp = new RegistrationResponse();
  
regResp.setSuccess(true);
regResp.setErrorCode(null);
regResp.setData("testdata");
regResp.setMessage("success");
  
ObjectMapper mapper = new ObjectMapper()
mapper.enable(SerializationFeature.INDENT_OUTPUT);
  
if(toExcludeNull) mapper.setSerializationInclusion(Include.NON_NULL);
else mapper.serializationInclusion(Include.ALWAYS);
  
String regRespStr = null;
try{
  
    regRespStr = mapper.writeValueAsString(regResp);
    }
    catch(JsonProcessingException e)
        e.printStackTrace();
        }
    System.out.println("Formatted JSON Response:" + regRespStr);


Here, regRespStr is the JSON String with NULL exclusion/inclusion applied.

You can also check the Github Repository.



Previous Article
Next Article

Similar Reads

Spring Boot - Customize the Jackson ObjectMapper
When using JSON format, Spring Boot will use an ObjectMapper instance to serialize responses and deserialize requests. In this article, we will take a look at the most common ways to configure the serialization and deserialization options. Let us do go through the default configuration. So by default, the Spring Boot configuration will be as follow
4 min read
How Jackson Data Binding Works in Spring Boot?
Spring is a framework of java that is used to build high-level, large-scale enterprise applications. And the most common thing we do in almost every application is transfer data between the front-end and back-end (to the server). Supposedly, when we perform Update, Create, or any other operation that impacts changes in the Database then what happen
4 min read
Convert Java Object to Json String using Jackson API
JSON stands for JavaScript Object Notation. It's a standard text-based format that shows structured data based on JavaScript object syntax. It is commonly used for transmitting data in web applications. JSON is highly recommended to transmit data between a server and web application. In order to convert a Java object into JSON, the following two me
3 min read
How to create a REST API using Java Spring Boot
Representational state transfer (REST) is a software architectural style that defines a set of constraints to be used for creating Web services. Web services that conform to the REST architectural style, called RESTful Web services, provide interoperability between computer systems on the Internet. RESTful Web services allow the requesting systems
6 min read
Spring Boot - REST API Documentation using OpenAPI
For any application, API documentation is essential for both users and developers. How to use an API, what will be the request body, and what will the API's response be? API documentation is the answer to all of these questions, springdoc-openapi is a Java library that automates the generation of the API documentation in both JSON/YAML and HTML for
4 min read
Spring Boot – REST API Documentation using Swagger
REST stands for Representational State Transfer. REST is an architectural design pattern that defines constraints that are used in web service development. Swagger is a framework in which we can test our REST APIs for different HTTP requests i.e. : GETPOSTPUTDELETEIn this article, we will be discussing using Swagger for documenting APIs in Spring B
4 min read
Easiest Way to Create REST API using Spring Boot
Spring Boot is a powerful framework that makes it easy to create RESTful APIs. In this article, we will go through a step-by-step guide on how to create a RESTful API in Spring Boot with MySQL and JPA. We will start by creating a new Spring Boot project and configuring it for our needs. For developers eager to deepen their knowledge and expertise i
11 min read
Spring Boot - How to set a Request Timeout for a REST API
In Microservice architecture, there are multiple microservices available for an application. For the application to work properly necessary services need to communicate with each other. There can be communication of messaging type or REST calls. How does REST API Work?In REST Calls the process is synchronous, which means suppose a service SERV1 is
7 min read
Spring Boot - Versioning a REST API
API Versioning is a defined process of making or managing changes to an API. These changes can be made transparently without interrupting the clients. When users have permission to decide whether they can conveniently upgrade to the latest version of API and clearly state the changes made is known as a Good API Versioning Strategy. When to Version
3 min read
Difference Between Spring Boot Starter Web and Spring Boot Starter Tomcat
Spring Boot is built on the top of the spring and contains all the features of spring. And is becoming a favorite of developers these days because of its rapid production-ready environment which enables the developers to directly focus on the logic instead of struggling with the configuration and setup. Spring Boot is a microservice-based framework
3 min read
configure() Method in Jackson in JSON
In Jackson, 'configure()' is a method that allows you to set various configuration options for the JSON parser and generator. The 'configure()' method can be called on an 'ObjectMapper' instance, which is the main class used for converting Java objects to and from JSON. 'ObjectMapper' is responsible for reading and writing JSON data in Java. The co
2 min read
Mapping a Dynamic JSON Object Field in Jackson with Java
All REST API services are providing the resultant output either as XML or JSON pattern only as both are portable in nature and among that JSON is more popular. We can expect unknown properties in a JSON object. There are different ways available to map dynamic JSON objects into Java classes. They are obviously required in many scenarios. Let us cov
5 min read
Java Spring Boot Microservices - Develop API Gateway Using Spring Cloud Gateway
The API Gateway Pattern in some cases stands for “Backend for frontend”. It is basically the entry gate for taking entry into any application by an external source. The pattern is going on in a programmer’s mind while they are making the client’s application. It acts as a medium between the client applications and microservices. For example-Netflix
4 min read
Spring Boot - Spring JDBC vs Spring Data JDBC
Spring JDBC Spring can perform JDBC operations by having connectivity with any one of jars of RDBMS like MySQL, Oracle, or SQL Server, etc., For example, if we are connecting with MySQL, then we need to connect "mysql-connector-java". Let us see how a pom.xml file of a maven project looks like. C/C++ Code <?xml version="1.0" encoding=
4 min read
Spring vs Spring Boot vs Spring MVC
Are you ready to dive into the exciting world of Java development? Whether you're a seasoned pro or just starting out, this article is your gateway to mastering the top frameworks and technologies in Java development. We'll explore the Spring framework, known for its versatility and lightweight nature, making it perfect for enterprise-level softwar
8 min read
How to Make REST Calls using FeignClient in Spring Boot?
Representational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services in a simple and flexible way without having any processing. FeignClient also known as Spring Cloud OpenFeign is a Declarative REST Client in Spring Boot Web Application.
13 min read
Spring Boot - REST Example
We all know in today's world, most web app follows the client-server architecture. The app itself is the client or frontend part under the hood it needs to call the server or the backend to get or save the data this communication happens using HTTP protocol the same protocol is the power of the web. On the server, we expose the bunch of services th
4 min read
How to Call REST Services with WebClient in Spring Boot?
Representational State Transfer (REST) is an architectural style that defines a set of constraints to be used for creating web services. REST API is a way of accessing web services in a simple and flexible way without having any processing. Spring WebClient is a non-blocking and reactive web client to perform HTTP requests. It is also the replaceme
11 min read
Spring - REST JSON Response
REST APIs are becoming popular for the advantages they provide in the development of applications. REST APIs work like a client-server architecture. The client makes a request and a server (REST API) responds back by providing some kind of data. A client can be any front-end framework like Angular, React, etc, or Spring application ( internal/exter
6 min read
Spring MVC - Get Probability of a Gender by Providing a Name using REST API
A lot of funful REST API calls are available as open source. Suppose if we like to keep a name to our nears and dears, we can just check that by means of a REST API call and get the gender, what is the probability of being that gender and how many times does it come with it? Relevant REST API call https://api.genderize.io?name=<Provide your desi
7 min read
Spring MVC - Get Exchange Rate Values using REST API
People are doing business, and developing software for geographical locations. That means the calculation of a software price will vary globally. During those scenarios, we need to know about the exchange rates for a given currency. Nowadays many open source REST API calls are available and among that there is a call available to get exchange rates
5 min read
OpenSource REST API URL and Retrieving Data From it By Using Spring MVC
In this internet era, a lot of helper services are available in the form of REST API and mostly REST API provides us the details in the form of JSON/XML. We can use them in our applications and render the data as we like. Here is the list of a few opensource REST API URLs: API NameDescriptionURLCoinGeckoExchange rates https://api.coingecko.com/api/
6 min read
Spring MVC - Getting Cryptocurrency Details using REST API
Cryptocurrencies are a hot topic throughout the world. Trading with cryptocurrency got both pros and cons. Nowadays REST APIs are very useful to get much information including cryptocurrencies. In this article, we are going to see about one such REST API call to get cryptocurrency detail. We are going to retrieve the information by using Spring MVC
5 min read
Get Time Zone by Providing Latitude and Longitude using Spring MVC and REST API
Spring MVC Framework follows the Model-View-Controller design pattern. It is used to develop web applications. It works around DispatcherServlet. DispatcherServlet handles all the HTTP requests and responses. In this article, we are going to see about a REST API call to find the coordinates for the given latitude and longitude. Each and every area
6 min read
Spring MVC - Comparison of Cryptocurrencies using REST API
REST APIS is available in plenty nowadays. As cryptocurrencies are a hot topic nowadays, there is always a need to compare the different cryptocurrencies and get the corresponding value in different currencies. As a sample, let us take a REST API call as https://min-api.cryptocompare.com/data/price?fsym=LTC&tsyms=BTC,USD,EUR,INR Here fym repres
6 min read
Spring MVC - Last 24 Hour Cryptocurrency Data using REST API
Cryptocurrencies are a hot topic now and in the future; they may also be a payment source. Hence a lot of research is getting done. Many REST APIs are available to provide data in JSON format. We are going to see one such REST API as https://api.wazirx.com/sapi/v1/ticker/24hr?symbol=<Need to provide the symbol of cryptocurrency> Example: http
5 min read
Spring MVC Project - Retrieving Population, Area and Region Details using Rest API
REST API is more popular nowadays as we can able to get a variety of information like Population, Area, region, sub-region, etc., One such REST API that we are going to see here is https://restcountries.com/v3.1/capital/<any capital of a country> Example: https://restcountries.com/v3.1/capital/delhi Corresponding JSON Response: As a Maven Spr
4 min read
Spring Boot | How to consume JSON messages using Apache Kafka
Apache Kafka is a stream processing system that lets you send messages between processes, applications, and servers. In this article, we will see how to publish JSON messages on the console of a Spring boot application using Apache Kafka. In order to learn how to create a Spring Boot project, refer to this article. Working Steps Step 1: Go to Sprin
3 min read
How to Create A REST API With JSON Server ?
Setting up a RESTful API using JSON Server, a lightweight and easy-to-use tool for quickly prototyping and mocking APIs. JSON Server allows you to create a fully functional REST API with CRUD operations (Create, Read, Update, Delete) using a simple JSON file as a data source. Table of Content GET Request Returns a List of all UsersPOST Request to c
4 min read
Spring Boot | How to access database using Spring Data JPA
Spring Data JPA is a method to implement JPA repositories to add the data access layer in applications easily. CRUD stands for create, retrieve, update, delete which are the possible operations which can be performed in a database. In this article, we will see an example of how to access data from a database(MySQL for this article) in a spring boot
4 min read
Article Tags :
Practice Tags :