Jackson JSON notes

Russell Bateman
March 2019
last update:

Jackson is a very good JSON utility library for Java.

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.9.8</version>                       <-- 18 December 2018 -->
</dependency>

The dependency above will cause the following to load:

public class Car
{
  private String color;
  private String type;

  // standard accessors...
}

Serialization of a POJO (bean) into JSON:

ObjectMapper mapper = new ObjectMapper();
Car          car    = new Car( "Yellow", "Renault" );
final String JSON   = mapper.writeValueAsString( car );

Deserialization of JSON input (string) to POJO (bean):

final String JSON = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
Car          car  = mapper.readValue( JSON, Car.class );

For (lots) more, see https://www.baeldung.com/jackson-object-mapper-tutorial.

Annotations

Tailoring Jackson behavior

Here are some examples. These can be used to extend new ObjectMapper() with .disable( ... ) or .enable( ... ), etc.

  • MapperFeature.ALLOW_COERCION_OF_SCALARS —basically, stuff like "json_boolean" : true instead of "json_boolean" : 1.
  • SerializationFeature.WRITE_DATES_AS_TIMESTAMPS —deals with whether Date-based things are serialized as numeric timestamps or as a textual representation.
  • DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES —unknown properties are ones that do not map to a property in the sense that there is no setter annotated to handle it, results in a failure.