Part 3: @JsonInclude and @JsonFormat; ISO-8601 is already the default
This commit is contained in:
@@ -0,0 +1,46 @@
|
|||||||
|
package com.ankurm.jackson3.part3annotations;
|
||||||
|
|
||||||
|
import com.fasterxml.jackson.annotation.JsonFormat;
|
||||||
|
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||||
|
import tools.jackson.databind.json.JsonMapper;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
import java.util.List;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Post: Jackson Annotations Cheat Sheet — https://ankurm.com/jackson-annotations-guide/
|
||||||
|
* Sections: "@JsonInclude" and "@JsonFormat"
|
||||||
|
*
|
||||||
|
* One correction to the post: it says "Without @JsonFormat, Jackson writes LocalDate
|
||||||
|
* as a numeric array by default." That was true in Jackson 2. In Jackson 3, java.time
|
||||||
|
* support is built in and ISO-8601 is the default — the annotation is only needed for
|
||||||
|
* a NON-standard pattern. The `defaultDate` field below proves it.
|
||||||
|
*/
|
||||||
|
public class D02InclusionAndFormat {
|
||||||
|
|
||||||
|
@JsonInclude(JsonInclude.Include.NON_NULL)
|
||||||
|
public record ProductDetails(String productName, String productDescription, Double discountRate) { }
|
||||||
|
|
||||||
|
@JsonInclude(JsonInclude.Include.NON_EMPTY)
|
||||||
|
public record CompactProduct(String productName, String notes, List<String> tags) { }
|
||||||
|
|
||||||
|
public record InvoiceRecord(
|
||||||
|
Long invoiceId,
|
||||||
|
LocalDate defaultDate, // no annotation
|
||||||
|
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd/MM/yyyy")
|
||||||
|
LocalDate ukStyleDate, // custom pattern
|
||||||
|
@JsonFormat(shape = JsonFormat.Shape.STRING)
|
||||||
|
double totalAmount) { } // number as string
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
JsonMapper mapper = JsonMapper.builder().build();
|
||||||
|
|
||||||
|
System.out.println("NON_NULL : "
|
||||||
|
+ mapper.writeValueAsString(new ProductDetails("Keyboard", null, null)));
|
||||||
|
System.out.println("NON_EMPTY : "
|
||||||
|
+ mapper.writeValueAsString(new CompactProduct("Keyboard", "", List.of())));
|
||||||
|
|
||||||
|
System.out.println("formats : " + mapper.writeValueAsString(new InvoiceRecord(
|
||||||
|
500L, LocalDate.of(2026, 4, 9), LocalDate.of(2026, 4, 9), 199.99)));
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user