Oevrview of JSON Serialization
In modern application development, data exchange often requires converting Java objects into JSON format and vice versa. Spring Boot automatically integrates the Jackson library for this purpose, providing seamless support for HTTP message converters. While default configurations cover most scenarios, developers frequently need to customize how data is represented.
Common Jackson Annotations
To control the serialization process, Jackson offers several annotations that modify field naming, exclusion rules, and value formatting.
- @JsonProperty: Renames a specific field in the resulting JSON document.
- @JsonIgnore: Excludes a single property entirely from serialization or deserialization.
- @JsonIgnoreProperties: Allows specifying multiple fields to omit.
- @JsonFormat: Defines patterns for dates and time values.
@JsonIgnore // Hides inventory count from public JSON view
private int stockQuantity;
@JsonProperty("item_id") // Maps to 'item_id' in JSON output
private String uuid;
@JsonFormat(pattern = "yyyy-MM-dd'T'HH:mm:ss")
private Date updateTimestamp;
}
</div>### Customizing the ObjectMapper
For global settings affecting all serialization tasks, you can define a dedicated configuration bean. This allows you to enforce consistent date formats and exclude null values across the entire application without repeating annotations.
<div>```
package com.example.config;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.text.SimpleDateFormat;
@Configuration
public class JsonSerializationConfig {
@Bean
public ObjectMapper customObjectMapper() {
ObjectMapper mapper = new ObjectMapper();
// Do not include properties with null values
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
// Set a global date format
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
mapper.setDateFormat(dateFormat);
mapper.configure(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
return mapper;
}
}
To utilize the customized configuration, inject the configured ObjectMapper into your service or controller layer. The following example demonstrates a manual serialization round-trip to verify that the custom settings apply correctly.
import com.example.model.InventoryItem; import com.fasterxml.jackson.databind.ObjectMapper; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController;
import java.util.Date; import java.util.UUID;
@Slf4j @RestController @RequestMapping("/api/data") public class DataProcessorController {
@Autowired
private ObjectMapper objectMapper;
@GetMapping("/process-item")
public InventoryItem demonstrateConversion() throws Exception {
// Instantiate object
InventoryItem item = InventoryItem.builder()
.productName("Smart Sensor")
.uuid(UUID.randomUUID().toString())
.updateTimestamp(new Date())
.build();
// Manual Serialization
String jsonString = objectMapper.writeValueAsString(item);
log.info("Serialized Payload: {}", jsonString);
// Manual Deserialization
InventoryItem restoredItem = objectMapper.readValue(jsonString, InventoryItem.class);
// Return the reconstructed object
return restoredItem;
}
}
</div>This setup ensures that when the endpoint is accessed, the returned data adheres to the defined business rules regarding null exclusino and timestamp formatting.