Jackson JSON notes

Russell Bateman
March 2019
last update: 03/11/2019 22:27:15

Jackson is a very good JSON utility library for Java.

1.<dependency>
2.  <groupId>com.fasterxml.jackson.core</groupId>
3.  <artifactId>jackson-databind</artifactId>
4.  <version>2.9.8</version>                       <-- 18 December 2018 -->
5.</dependency>

The dependency above will cause the following to load:

1.public class Car
2.{
3.  private String color;
4.  private String type;
5. 
6.  // standard accessors...
7.}

Serialization of a POJO (bean) into JSON:

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

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

1.final String JSON = "{ \"color\" : \"Black\", \"type\" : \"BMW\" }";
2.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.