How to manage JSON Data in Spring Boot with Jackson project

In this tutorial we will learn how to produce and consume JSON data in a Spring Boot applications using the built-in Jackson provider.

Jackson project provides first class support for standard format such as XML and JSON. Spring Framework and Spring Boot have built-in support for Jackson based JSON and XML serialization/deserialization.

Consider the following Spring Boot Controller class:

@RestController
public class CustomerController {
  @Autowired CustomerRepository repository;

  @RequestMapping("/list")
  public List<Customer> findAll() {
    return repository.getData();
  }

  @RequestMapping("/one/{id}")
  public Customer findOne(@PathVariable int id) {
    return repository.getData().get(id);
  }
}

Assumed that the Customer object is created in the following way:

@Component public class CustomerRepository {
  List < Customer > customerList = new ArrayList < Customer > ();
  @PostConstruct public void init() {
      try {
        customerList.add(new Customer(1, "frank"); customerList.add(new Customer(2, "john");
          }
          catch (ParseException e) {
            e.printStackTrace();
          }
        }
        public List < Customer > getData() {
          return customerList;
        }
      }

Then, when requesting the URL http://localhost:8080/list the following JSON data will be returned:

[      {         "id": 1,         "name": "frank"     },     {         "id": 2,         "name": "john"     }  ] 

There is no need to add any jackson-core,jackson-annotations and jackson-databind as their jars are automatically added by Spring Boot:

jar tvf demo-rest-0.0.1-SNAPSHOT.jar    . . . .  1348389 Tue Aug 06 01:41:54 CEST 2019 BOOT-INF/lib/jackson-databind-2.9.9.3.jar  66519 Sat Jul 29 20:53:26 CEST 2017 BOOT-INF/lib/jackson-annotations-2.9.0.jar 325632 Wed May 15 19:58:38 CEST 2019 BOOT-INF/lib/jackson-core-2.9.9.jar  33429 Thu May 16 03:26:48 CEST 2019 BOOT-INF/lib/jackson-datatype-jdk8-2.9.9.jar 100674 Thu May 16 03:27:12 CEST 2019 BOOT-INF/lib/jackson-datatype-jsr310-2.9.9.jar   8645 Thu May 16 03:26:28 CEST 2019 BOOT-INF/lib/jackson-module-parameter-names-2.9.9.jar 

Using Jackson annotations

As said, if you are ok with the default Jackson serialization/deserialization, there is no need to add any extra dependency. On the other hand, if you want to use Jackson annotations in your code, to compile the application it is required to add a Jackson dependency.

Let’s create a more complex Customer object:

public class Customer {     @JsonIgnore     private int id;      @JsonProperty("customer_name")     private String name;      @JsonSerialize(using = CustomDateSerializer.class)     public Date birthDate;      public Customer(int id, String name, Date birthDate) {         this.id = id;         this.name = name;         this.birthDate = birthDate;     }     
// Getter/Setters omitted for brevity 
} 

This class contains the following annotations:

  • @com.fasterxml.jackson.annotation.JsonIgnore: This annotation indicates that the property is to be ignored by introspection-based serialization and deserialization functionality.
  • @com.fasterxml.jackson.annotation.JsonProperty: This annotation can be used to provide a custom name field name in JSON objects
  • @com.fasterxml.jackson.databind.annotation.JsonSerialize: This annotation can be used to provide a custom Java class to serialize the content of JSON object.
public class CustomDateSerializer extends StdSerializer<Date> {
  private static SimpleDateFormat formatter = new SimpleDateFormat("EEEEE MMMMM yyyy");

  public CustomDateSerializer() {
    this(null);
  }

  public CustomDateSerializer(Class<Date> t) {
    super(t);
  }

  @Override
  public void serialize(Date value, JsonGenerator gen, SerializerProvider arg2)
      throws IOException, JsonProcessingException {
    gen.writeString(formatter.format(value));
  }
}

This time, the extra Date field will be included in the Constructor of the Customer class:

@PostConstruct public void init() {
  try {
    customerList.add(new Customer(1, "frank", new SimpleDateFormat("dd/MM/yyyy").parse("17/10/1970")));
    customerList.add(new Customer(2, "john", new SimpleDateFormat("dd/MM/yyyy").parse("25/07/1980")));
  } catch (ParseException e) {
    e.printStackTrace();
  }
}

The result of (http://localhost:8080/list), will be the following JSON data:

[      {         "birthDate": "Saturday October 1970",         "customer_name": "frank"     },     {         "birthDate": "Friday July 1980",         "customer_name": "john"     }  ] 

In order to compile your example, you will need to include the following extra dependency:

<?xml version="1.0" encoding="UTF-8"?><project>
   <dependency>
       	
      <groupId>com.fasterxml.jackson.core</groupId>
       	
      <artifactId>jackson-core</artifactId>
       	
      <version>2.9.8</version>
       
   </dependency>
    
</project>

That’s all. The source code for this Spring Boot Jackson example is available here: https://github.com/fmarchioni/masterspringboot/tree/master/json/demo-jackson