Jackson

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 use JsonNode.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 to javac 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 if ParameterNamesModule is registered. If not, add a Spring bean of ParameterNamesModule to register it with ObjectMapper.

      @Bean
      public com.fasterxml.jackson.databind.Module parameterNamesModule() {
          return new ParameterNamesModule(JsonCreator.Mode.PROPERTIES);
      }
  • Pros

    1. Little to no code or config changes needed
    2. Doesn't need access to the source code of classes being deserialized
  • Cons

    1. Potential performance implications
    2. 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 existing ObjectMapper
  • Pros

    1. Full control over deserialization
    2. Doesn't have Java version requirement
  • Cons

    1. A lot more efforts needed to implement a deserializer right

Different JSON serialization views on the same object