- Example of "idiomatic" Jackson compatible Java 8-17 POJO
- See also, detailed explanation
- See also, non-Jackson POJO example
- See also, Lombok POJO examples
/**
* TODO: add a BRIEF description of purpose
* TODO: if this POJO aligns with a DB table, mention that here
*/
@JsonDeserialize(builder = Employee.Builder.class)
@JsonPropertyOrder(alphabetic = true)
public final class Employee {
private final boolean active;
/**
* [16, 100]
*/
private final int age;
/**
* [a-zA-Z-]{2,64}
* eg. "Wil"
*/
private final String name;
@JsonProperty("firstDayOnTheJob")
private final LocalDate startDate;
private Employee(Builder builder) {
// Example of default value
active = Optional.ofNullable(builder.active).orElse(true);
age = builder.age;
name = builder.name;
startDate = builder.startDate;
// -- Validations
checkArgument(age <= 100, "age is too high: " + age);
checkArgument(age >= 16, "age is too low: " + age);
checkArgument(isNotBlank(name), "name is required");
requireNonNull(startDate, "startDate is required and missing.");
//TODO: other validations go here
}
// NOTE: Generated getters, hashcode, equals, toString appear around here
// (Almost) Everything below is generated by Innerbuilder plugin ...
public static Builder newBuilder() {
return new Builder();
}
public static Builder newBuilder(Employee copy) {
Builder builder = new Builder();
builder.active = copy.active;
builder.age = copy.age;
builder.name = copy.name;
builder.startDate = copy.startDate;
return builder;
}
// NOTE: Notice the annotations below
@JsonIgnoreProperties({"\u0024schema", "\u0024id"})
@JsonPOJOBuilder(withPrefix = "")
public static final class Builder {
// notice the object type allows defaulting active to true
private Boolean active;
private int age;
private String name;
// NOTE: Notice the annotation below
@JsonProperty("firstDayOnTheJob")
private LocalDate startDate;
private Builder() {
}
public Builder active(boolean active) {
this.active = active;
return this;
}
public Builder age(int age) {
this.age = age;
return this;
}
public Employee build() {
return new Employee(this);
}
public Builder name(String name) {
this.name = name;
return this;
}
public Builder startDate(LocalDate startDate) {
this.startDate = startDate;
return this;
}
}
}
ObjectMapper objectMapper = ...
Employee wil = Employee.newBuilder()
.age(35)
.name("Wil C")
.startDate(LocalDate.of(2020, 01, 31))
.build();
// NOTE: wil.active is defaulted to true
System.out.println(
objectMapper.writeValueAsString(wil));