1
0

Part 1 extra: POJOs serialise alphabetically, records do not

This commit is contained in:
2026-08-04 17:29:51 +00:00
parent 97d54d33a1
commit a5c3179cd1

View File

@@ -0,0 +1,50 @@
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)));
}
}