Jackson Databind - Cheatsheet
Deserialization
Deserialization - If you don't want to create a new type, use JsonNode
- Use
JsonNode
to deserialize JSON to a tree structure, and then useJsonNode.get("key")
to get the value of a key.
Deserialization - Spring troubleshooting
-
Debug
org.springframework.http.codec.json.AbstractJackson2Decoder.canDecode
com.fasterxml.jackson.databind.DeserializationContext.hasValueDeserializerFor
Spring Boot
Expose ID for domain types
- Use
RepositoryRestConfiguration.exposeIdsFor
to config - Relevant Jackson 2 Module is `PersistentEntityJackson2Module``
Deserialization of POJOs with final fields and constructors
- POJOs with final fields and constructors are usually immutable objects used as DTOs.
Solution 1 - Use JEP 118: Access to Parameter Names at Runtime
-
Steps
-
Add dependency
com.fasterxml.jackson.module:jackson-module-parameter-names
. -
Configure the build tool to add
-parameters
flag tojavac
when compiling source code.<plugin> <artifactId>maven-compiler-plugin</artifactId> <configuration> <parameters>true</parameters> </configuration> </plugin>
-
Set
spring.jackson.constructor-detector: USE_PROPERTIES_BASED
. -
Check
JacksonAutoConfiguration
to see ifParameterNamesModule
is registered. If not, add a Spring bean ofParameterNamesModule
to register it withObjectMapper
.@Bean public com.fasterxml.jackson.databind.Module parameterNamesModule() { return new ParameterNamesModule(JsonCreator.Mode.PROPERTIES); }
-
-
Pros
- Little to no code or config changes needed
- Doesn't need access to the source code of classes being deserialized
-
Cons
- Potential performance implications
- Requires Java 8+
Solution 2 - Implement a custom deserializer
-
Steps
- Implement a custom deserializer by extending
StdDeserializer
- Add
@JsonComponent
to the deserializer class, and ensure the class is in a package being scanned for Spring bean, and the deserializer will be register with the existingObjectMapper
- Implement a custom deserializer by extending
-
Pros
- Full control over deserialization
- Doesn't have Java version requirement
-
Cons
- A lot more efforts needed to implement a deserializer right
Different JSON serialization views on the same object
-
Use
@JsonView
annotation