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.
@JsonInclude( JsonInclude.Include.ALWAYS ) // always include this field private UUID id; @JsonInclude( JsonInclude.Include.NON_NULL ) // include this field when not nil private Ojbect metadata; @JsonInclude( JsonInclude.Include.NON_EMPTY ) // include this field when not null or empty private String version; @JsonInclude( JsonInclude.Include.NON_DEFAULT ) // (see documentation)
private Map< String, String > properties; @JsonAnyGetter public Map< String, String > getProperties() { return properties; }
private String name; @JsonGetter( "name" ) public String getTheName() { return name; }
@JsonPropertyOrder( "name", "id", "date" ) public class Thing { private int id; private String name; private Date date; }