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.
2.3 KiB
Part 1 — ObjectMapper: reading and writing
Post: https://ankurm.com/jackson-objectmapper-guide/
B01 — writing
String, File and pretty-printed output.
{"articleId":1,"title":"Jackson Deep Dive","tags":["java","json"]}
file : {"articleId":1,"title":"Jackson Deep Dive","tags":["java","json"]}
pretty :
{
"articleId" : 1,
"title" : "Jackson Deep Dive",
"tags" : [ "java", "json" ]
}
B02 — reading
String, File and InputStream. The post's readValue(new URL(...), ...) example is
deliberately not reproduced — it makes a live network call, so it could not be part of
a reproducible run. The InputStream form is what an HTTP client hands you in practice.
from String : Jackson Deep Dive
from File : 1
from Stream : [java, json]
B03 — generic collections
TypeReference lives in tools.jackson.core.type in Jackson 3. The example also runs
the wrong version — readValue(json, List.class) — to show what it actually produces.
size : 2
element class : Article
first title : First
raw element : LinkedHashMap <- not Article
cast fails : ClassCastException, as expected
map value : Nine
The failure is deferred, not immediate: the call succeeds and returns a
List<LinkedHashMap>. You find out at the first cast, often far from the parse site.
B04 — property ordering
Beyond the post, but it explains why your first output does not look like the article's.
POJO : {"listPrice":79.99,"productId":1,"productName":"Mechanical Keyboard"}
record : {"productId":1,"productName":"Mechanical Keyboard","listPrice":79.99}
ordered : {"productId":1,"productName":"Mechanical Keyboard","listPrice":79.99}
Getter-based POJOs serialise alphabetically; records follow declaration order;
@JsonPropertyOrder overrides both. Worth pinning explicitly if the JSON is
cached, signed, or diffed against a fixture.