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.
@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; }