Jackson JSON notes

Russell Bateman
March 2019
last update:

Jackson is a very good JSON utility library for Java.

  <version>2.9.8</version>                       <-- 18 December 2018 -->

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.


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.