1. Core dependency
Spring Boot integrates Jackson by default, no additional dependencies are required:
<!-- If using Spring Boot Starter Web --> <dependency> <groupId></groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
2. Basic usage
2.1 Object to JSON (serialization)
ObjectMapper mapper = new ObjectMapper(); User user = new User("Zhang San", 25); String json = (user); // Output: {"name":"Zhang San","age":25}
2.2 JSON to object (deserialization)
String json = "{\"name\":\"Li Si\",\"age\":30}"; User user = (json, );
3. Common annotations
3.1 Field Control
public class User { @JsonProperty("user_name") // Custom JSON field name private String name; @JsonIgnore // Ignore fields private String password; @JsonInclude(.NON_NULL) // Non-empty time serialization private String email; }
3.2 Time format
public class Order { @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private LocalDateTime createTime; }
3.3 Polymorphic processing
@JsonTypeInfo(use = , property = "type") @JsonSubTypes({ @Type(value = , name = "cat"), @Type(value = , name = "dog") }) public abstract class Animal {}
4. Custom configuration (Spring Boot)
4.1 Global configuration
@Configuration public class JacksonConfig { @Bean public ObjectMapper objectMapper() { return new ObjectMapper() .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) // Date does not convert to timestamp .enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT) .setSerializationInclusion(.NON_NULL); } }
4.2 Configuration item example
# spring: jackson: date-format: yyyy-MM-dd HH:mm:ss time-zone: GMT+8 default-property-inclusion: non_null deserialization: FAIL_ON_UNKNOWN_PROPERTIES: false # Ignore unknown fields
5. Advanced Tips
5.1 Handling generics
TypeReference<ResultDTO<List<User>>> typeRef = new TypeReference<>() {}; ResultDTO<List<User>> result = (json, typeRef);
5.2 Streaming API (processing large files)
JsonFactory factory = (); try (JsonParser parser = (new File(""))) { while (() != null) { // Handle it one by one } }
5.3 Custom Serializer
public class MoneySerializer extends JsonSerializer<BigDecimal> { @Override public void serialize(BigDecimal value, JsonGenerator gen, SerializerProvider provider) { ((2, RoundingMode.HALF_UP) + "Yuan"); } } // Use annotationpublic class Product { @JsonSerialize(using = ) private BigDecimal price; }
6. Frequently Asked Questions
6.1 Circular reference problem
// Method 1: Use @JsonIgnore to break the looppublic class Order { @JsonIgnore private User user; } // Method 2: Configure global ignorance(SerializationFeature.FAIL_ON_SELF_REFERENCES, false);
6.2 Enumeration processing
public enum Status { @JsonValue // Use code when serializing OK(1), ERROR(2); private final int code; // Convert according to code during deserialization @JsonCreator public static Status fromCode(int code) { /* ... */ } }
6.3 Handling special characters
(.ESCAPE_NON_ASCII, true); // Input: {"name":"Zhang San"} → Output: {"name":"\u5F20\u4E09"}
7. Performance optimization
7.1 Enable cache
(MapperFeature.USE_ANNOTATIONS); (MapperFeature.CAN_OVERRIDE_ACCESS_MODIFIERS);
7.2 Thread-safe configuration
ObjectMapper mapper = new ObjectMapper(); // Configure as thread safe(new JavaTimeModule()); (SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
7.3 Using third-party modules
<dependency> <groupId></groupId> <artifactId>jackson-datatype-jsr310</artifactId> </dependency>
ObjectMapper mapper = new ObjectMapper().registerModule(new JavaTimeModule());
8. Safety precautions
8.1 Prevent XXE attacks
(.ALLOW_EXTERNAL_PROCESSING, false);
8.2 Deserialization protection
// Enable type checking(.NON_FINAL); // Or use the annotation @JsonTypeInfo
Best Practice Summary
- Unified configuration: Ensure consistency through ObjectMapper global configuration
- Use annotations reasonably: Avoid excessive annotations causing code contamination
- Performance monitoring: Serialized performance testing of high-frequency interfaces
- Version management: Timely upgrade Jackson version fix vulnerabilities
Through the above methods, JSON data can be processed efficiently and safely.
This is the article about the newbie's guide to using Jackson for JSON generation and parsing. For more related Jackson JSON content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!