37 runnable examples covering the eight feature posts on ankurm.com, verified against Jackson 3.2.1 on Temurin 21.0.5. Every output committed under docs/ was produced by run-all.sh. Also documents 11 places where the published snippets do not compile or do not behave as printed against a real Jackson 3 build - most notably that writeValueAsString(List<Base>) silently drops the polymorphic type discriminator, so the post's serialised output cannot be read back.
51 lines
2.2 KiB
Java
51 lines
2.2 KiB
Java
package com.ankurm.jackson3.part1objectmapper;
|
|
|
|
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
|
|
import tools.jackson.databind.json.JsonMapper;
|
|
|
|
/**
|
|
* BEYOND THE POST — no blog section covers this, but it bites on first run.
|
|
*
|
|
* A record serialises in declaration order. A getter-based POJO serialises in
|
|
* ALPHABETICAL order. If you are diffing Jackson output against a fixture, this
|
|
* is usually the reason the diff is not empty.
|
|
*/
|
|
public class B04PropertyOrdering {
|
|
|
|
/** Getter-based POJO: output is alphabetical, NOT declaration order. */
|
|
public static class ProductPojo {
|
|
private Long productId;
|
|
private String productName;
|
|
private double listPrice;
|
|
public ProductPojo(Long i, String n, double p) { productId = i; productName = n; listPrice = p; }
|
|
public Long getProductId() { return productId; }
|
|
public String getProductName() { return productName; }
|
|
public double getListPrice() { return listPrice; }
|
|
}
|
|
|
|
/** Record: output follows the component declaration order. */
|
|
public record ProductRecord(Long productId, String productName, double listPrice) { }
|
|
|
|
/** Explicit ordering wins over both defaults. */
|
|
@JsonPropertyOrder({ "productId", "productName", "listPrice" })
|
|
public static class ProductOrdered {
|
|
private final Long productId;
|
|
private final String productName;
|
|
private final double listPrice;
|
|
public ProductOrdered(Long i, String n, double p) { productId = i; productName = n; listPrice = p; }
|
|
public Long getProductId() { return productId; }
|
|
public String getProductName() { return productName; }
|
|
public double getListPrice() { return listPrice; }
|
|
}
|
|
|
|
public static void main(String[] args) {
|
|
JsonMapper mapper = JsonMapper.builder().build();
|
|
System.out.println("POJO : " + mapper.writeValueAsString(
|
|
new ProductPojo(1L, "Mechanical Keyboard", 79.99)));
|
|
System.out.println("record : " + mapper.writeValueAsString(
|
|
new ProductRecord(1L, "Mechanical Keyboard", 79.99)));
|
|
System.out.println("ordered : " + mapper.writeValueAsString(
|
|
new ProductOrdered(1L, "Mechanical Keyboard", 79.99)));
|
|
}
|
|
}
|