objectmapper-jsonmapper: Jackson 2.23.0 vs 3.3.0 side by side (ObjectMapper/JsonMapper guide rewrite)
Seven runnable programs P01-P07 plus five compile-failure files, JDK 25, no docs/ folder. Output in objectmapper-jsonmapper/output/ is regenerated by scripts/run-all.sh. Co-Authored-By: Claude Sonnet 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_017ic4b75Ao6imWN5bj7FHVw
This commit is contained in:
@@ -0,0 +1,52 @@
|
||||
# objectmapper-jsonmapper
|
||||
|
||||
Runnable companion for the ankurm.com guide
|
||||
[Jackson ObjectMapper and JsonMapper (Jackson 2 and 3)](https://ankurm.com/jackson-objectmapper-guide/).
|
||||
Jackson 2 and Jackson 3 sit side by side on one classpath (they live in different packages), so the
|
||||
same input goes through both mappers in the same JVM and the output can be compared line by line.
|
||||
There is deliberately no `docs/` folder: all explanation lives in the post, and every number in it
|
||||
comes from a file in [`output/`](output).
|
||||
|
||||
```
|
||||
Jackson 3 3.3.0 tools.jackson.core:jackson-databind
|
||||
Jackson 2 2.23.0 com.fasterxml.jackson.core:jackson-databind (+ jsr310 for the java.time demo)
|
||||
jackson-annotations 2.23 com.fasterxml.jackson.core (shared by both majors, pulled in by Jackson 3)
|
||||
JDK Temurin 25.0.5+8
|
||||
```
|
||||
|
||||
Both 3.3.0 and 2.23.0 appeared on Maven Central on 2026-11-08 (directory listing of repo1.maven.org).
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
cd objectmapper-jsonmapper
|
||||
./scripts/run-all.sh # compiles, runs P01-P07, compiles the broken/ files, rewrites output/
|
||||
```
|
||||
|
||||
Single program: `mvn -q compile` then
|
||||
`java -cp "target/classes:$(cat target/cp.txt)" com.ankurm.objectmapper.P03ReadWriteCookbook`
|
||||
(run `run-all.sh` once first so `target/cp.txt` exists).
|
||||
|
||||
Timing lines in `P07` are indicative and move between runs; everything else reproduces exactly.
|
||||
|
||||
## Programs
|
||||
|
||||
| File | What it shows | Output |
|
||||
|---|---|---|
|
||||
| [`Article.java`](src/main/java/com/ankurm/objectmapper/Article.java) | the annotation-free POJO every example uses | - |
|
||||
| [`P01TwoMappersSideBySide`](src/main/java/com/ankurm/objectmapper/P01TwoMappersSideBySide.java) | same write/read in both majors, and which classes they really are | [output](output/P01TwoMappersSideBySide.txt) |
|
||||
| [`P02ImmutableMapper`](src/main/java/com/ankurm/objectmapper/P02ImmutableMapper.java) | why Jackson 3 has no setters; `rebuild()`; Jackson 2 ignoring a late setting | [output](output/P02ImmutableMapper.txt) |
|
||||
| [`P03ReadWriteCookbook`](src/main/java/com/ankurm/objectmapper/P03ReadWriteCookbook.java) | String/byte[]/File/Path/streams, `TypeReference`, tree, `convertValue`, readers | [output](output/P03ReadWriteCookbook.txt) |
|
||||
| [`P04ConfigRecipes`](src/main/java/com/ankurm/objectmapper/P04ConfigRecipes.java) | defaults of both majors read from the enums, property order, the config recipe | [output](output/P04ConfigRecipes.txt) |
|
||||
| [`P05JavaTime`](src/main/java/com/ankurm/objectmapper/P05JavaTime.java) | `java.time` with and without the module | [output](output/P05JavaTime.txt) |
|
||||
| [`P06Exceptions`](src/main/java/com/ankurm/objectmapper/P06Exceptions.java) | checked vs unchecked exceptions, same bad input | [output](output/P06Exceptions.txt) |
|
||||
| [`P07SharedMapperThreads`](src/main/java/com/ankurm/objectmapper/P07SharedMapperThreads.java) | one mapper across 8 threads; shared vs per-call cost | [output](output/P07SharedMapperThreads.txt) |
|
||||
| [`src/broken/`](src/broken) | five Jackson 2 habits that fail to compile on Jackson 3 | [compiler messages](output/Broken-compile-errors.txt) |
|
||||
|
||||
## Gradle
|
||||
|
||||
```groovy
|
||||
dependencies {
|
||||
implementation 'tools.jackson.core:jackson-databind:3.3.0'
|
||||
}
|
||||
```
|
||||
@@ -0,0 +1,39 @@
|
||||
=== Broken1MutateAfterBuild.java ===
|
||||
Broken1MutateAfterBuild.java:9: error: cannot find symbol
|
||||
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
|
||||
^
|
||||
Broken1MutateAfterBuild.java:10: error: cannot find symbol
|
||||
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
|
||||
^
|
||||
Broken1MutateAfterBuild.java:11: error: cannot find symbol
|
||||
mapper.enable(SerializationFeature.INDENT_OUTPUT);
|
||||
^
|
||||
3 errors
|
||||
|
||||
=== Broken2ReadValueUrl.java ===
|
||||
Broken2ReadValueUrl.java:7: error: no suitable method found for readValue(URL,Class<Object>)
|
||||
Object o = mapper.readValue(new java.net.URL("https://example.com/a.json"), Object.class);
|
||||
^
|
||||
1 error
|
||||
|
||||
=== Broken3CatchIOException.java ===
|
||||
Broken3CatchIOException.java:10: error: exception IOException is never thrown in body of corresponding try statement
|
||||
} catch (IOException e) {
|
||||
^
|
||||
1 error
|
||||
|
||||
=== Broken4JavaTimeModule.java ===
|
||||
Broken4JavaTimeModule.java:1: error: package tools.jackson.datatype.jsr310 does not exist
|
||||
import tools.jackson.datatype.jsr310.JavaTimeModule;
|
||||
^
|
||||
Broken4JavaTimeModule.java:7: error: cannot find symbol
|
||||
JsonMapper mapper = JsonMapper.builder().addModule(new JavaTimeModule()).build();
|
||||
^
|
||||
2 errors
|
||||
|
||||
=== Broken5WriteDatesAsTimestamps.java ===
|
||||
Broken5WriteDatesAsTimestamps.java:8: error: cannot find symbol
|
||||
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS).build();
|
||||
^
|
||||
1 error
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
Jackson 2 2.23.0 -> {"articleId":1,"title":"Jackson Deep Dive","tags":["java","json"],"subtitle":null}
|
||||
Jackson 3 3.3.0 -> {"articleId":1,"subtitle":null,"tags":["java","json"],"title":"Jackson Deep Dive"}
|
||||
identical JSON: false
|
||||
|
||||
Jackson 2 read title: Jackson Deep Dive
|
||||
Jackson 3 read title: Jackson Deep Dive
|
||||
|
||||
{
|
||||
"articleId" : 1,
|
||||
"subtitle" : null,
|
||||
"tags" : [ "java", "json" ],
|
||||
"title" : "Jackson Deep Dive"
|
||||
}
|
||||
|
||||
m2 class: com.fasterxml.jackson.databind.ObjectMapper
|
||||
m3 class: tools.jackson.databind.json.JsonMapper
|
||||
m3 superclass: tools.jackson.databind.ObjectMapper
|
||||
m3 is-a tools.jackson.databind.ObjectMapper: true
|
||||
@JsonInclude lives in: com.fasterxml.jackson.annotation
|
||||
@@ -0,0 +1,16 @@
|
||||
== public mutator methods on the mapper class ==
|
||||
Jackson 2 ObjectMapper : 47 distinct names
|
||||
Jackson 3 ObjectMapper : 1 distinct names
|
||||
Jackson 3 JsonMapper : 1 distinct names
|
||||
the one Jackson 3 name that matched: [registeredModules] (a getter, not a setter)
|
||||
|
||||
== Jackson 2: reconfigure after first use ==
|
||||
before : {"articleId":1,"title":"Jackson Deep Dive","tags":["java"],"subtitle":null}
|
||||
after setSerializationInclusion(NON_NULL) : {"articleId":1,"title":"Jackson Deep Dive","tags":["java"],"subtitle":null}
|
||||
fresh mapper, same setting : {"articleId":1,"title":"Jackson Deep Dive","tags":["java"]}
|
||||
|
||||
== Jackson 3: rebuild() derives a new mapper ==
|
||||
original : {"articleId":1,"subtitle":null,"tags":["java"],"title":"Jackson Deep Dive"}
|
||||
rebuilt NON_NULL : {"articleId":1,"tags":["java"],"title":"Jackson Deep Dive"}
|
||||
original again : {"articleId":1,"subtitle":null,"tags":["java"],"title":"Jackson Deep Dive"}
|
||||
same instance? : false
|
||||
@@ -0,0 +1,27 @@
|
||||
writeValueAsString : {"articleId":1,"subtitle":null,"tags":["java","json"],"title":"Jackson Deep Dive"}
|
||||
writeValueAsBytes : 82 bytes
|
||||
writeValue(Path) : {"articleId":1,"subtitle":null,"tags":["java","json"],"title":"Jackson Deep Dive"}
|
||||
writeValue(Stream) : 82 bytes
|
||||
|
||||
read String : Jackson Deep Dive
|
||||
read byte[] : Jackson Deep Dive
|
||||
read File : Jackson Deep Dive
|
||||
read Path : Jackson Deep Dive
|
||||
read InputStream : Jackson Deep Dive
|
||||
read Reader : Jackson Deep Dive
|
||||
|
||||
List<Article> size : 2, element class: Article
|
||||
List.class element : java.util.LinkedHashMap
|
||||
|
||||
tree title : Jackson Deep Dive
|
||||
tree tags[1] : json
|
||||
convertValue to Map : {articleId=1, subtitle=null, tags=[java, json], title=Jackson Deep Dive}
|
||||
convertValue to bean : 9 / From a Map
|
||||
|
||||
readerFor(Article) : Jackson Deep Dive
|
||||
pretty writer : {\n "k" : 1\n}
|
||||
|
||||
Jackson 2 readValue(URL, Class) exists : true
|
||||
Jackson 3 readValue(URL, Class) exists : false
|
||||
Jackson 3 readTree(URL) exists : false
|
||||
non-ASCII byte[] round trip equal : true (bytes are UTF-8 by default: true)
|
||||
@@ -0,0 +1,25 @@
|
||||
== default value of a few features (enabledByDefault) ==
|
||||
feature Jackson2 Jackson3
|
||||
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES true false
|
||||
SerializationFeature.FAIL_ON_EMPTY_BEANS true false
|
||||
SerializationFeature.INDENT_OUTPUT false false
|
||||
WRITE_DATES_AS_TIMESTAMPS (J2: SerializationFeature, J3: DateTimeFeature) true false
|
||||
DeserializationFeature.FAIL_ON_TRAILING_TOKENS false true
|
||||
MapperFeature.SORT_PROPERTIES_ALPHABETICALLY false true
|
||||
|
||||
Jackson 2 default : UnrecognizedPropertyException
|
||||
Jackson 3 default : accepted unknown field, title=T
|
||||
Jackson 3 strict : UnrecognizedPropertyException
|
||||
builderWithJackson2Defaults : UnrecognizedPropertyException (Jackson 2 behaviour back)
|
||||
|
||||
order J2 default : {"articleId":1,"title":"T","tags":["a"],"subtitle":"S"}
|
||||
order J3 default : {"articleId":1,"subtitle":"S","tags":["a"],"title":"T"}
|
||||
order J3 sorting disabled : {"articleId":1,"title":"T","tags":["a"],"subtitle":"S"}
|
||||
order J3 Jackson2Defaults : {"articleId":1,"title":"T","tags":["a"],"subtitle":"S"}
|
||||
|
||||
{
|
||||
"article_id" : 1,
|
||||
"tags" : [ "java", "json" ],
|
||||
"title" : "Jackson Deep Dive"
|
||||
}
|
||||
round trip articleId = 1
|
||||
@@ -0,0 +1,8 @@
|
||||
Jackson 2, no module : InvalidDefinitionException
|
||||
Java 8 date/time type `java.time.LocalDate` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling (or disable `MapperFeature.REQUIRE_HANDLERS_FOR_JAVA8_TIMES`) (through reference chain: java.util.LinkedHashMap["published"])
|
||||
Jackson 2 + JavaTimeModule : {"published":[2026,11,17],"at":1794876420.000000000}
|
||||
Jackson 2 + module + disable(TIMESTAMPS): {"published":"2026-11-17","at":"2026-11-17T00:47:00Z"}
|
||||
Jackson 3, plain JsonMapper : {"published":"2026-11-17","at":"2026-11-17T00:47:00Z"}
|
||||
Jackson 3 read LocalDate : 2026-11-17
|
||||
class NOT on classpath : tools.jackson.datatype.jsr310.JavaTimeModule
|
||||
class present on classpath : com.fasterxml.jackson.datatype.jsr310.JavaTimeModule
|
||||
@@ -0,0 +1,17 @@
|
||||
== class hierarchy ==
|
||||
J2 JsonProcessingException extends com.fasterxml.jackson.core.JacksonException -> extends java.io.IOException
|
||||
J3 JacksonException extends java.lang.RuntimeException
|
||||
|
||||
== malformed JSON ==
|
||||
J2 com.fasterxml.jackson.core.JsonParseException
|
||||
Unexpected character ('}' (code 125)): expected a valid value (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
|
||||
at line 1, column 27
|
||||
J3 tools.jackson.core.exc.StreamReadException
|
||||
Unexpected character ('}' (code 125)): expected a valid value (JSON String, Number, Array, Object or token 'null', 'true' or 'false')
|
||||
at line 1, column 27
|
||||
|
||||
== wrong value type ==
|
||||
J2 InvalidFormatException
|
||||
J3 InvalidFormatException (path: [articleId])
|
||||
|
||||
stream + lambda parsed 2 articles with no try/catch
|
||||
@@ -0,0 +1,5 @@
|
||||
8 threads x 20000 round trips on ONE JsonMapper, wrong results: 0
|
||||
|
||||
round 1: shared 3 ms, new mapper per call 878 ms (2000 reads each)
|
||||
round 2: shared 1 ms, new mapper per call 323 ms (2000 reads each)
|
||||
round 3: shared 1 ms, new mapper per call 217 ms (2000 reads each)
|
||||
@@ -0,0 +1,51 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<!-- Standalone module: build it from inside this directory. It is not part of the root
|
||||
pom. Jackson 2 and Jackson 3 sit side by side on one classpath on purpose: they live
|
||||
in different packages (com.fasterxml.jackson vs tools.jackson), so both mappers can
|
||||
be run in the same JVM and their output compared line by line. -->
|
||||
<groupId>com.ankurm</groupId>
|
||||
<artifactId>objectmapper-jsonmapper</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<packaging>jar</packaging>
|
||||
<name>objectmapper-jsonmapper</name>
|
||||
|
||||
<properties>
|
||||
<maven.compiler.release>25</maven.compiler.release>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<jackson2.version>2.23.0</jackson2.version>
|
||||
<jackson3.version>3.3.0</jackson3.version>
|
||||
</properties>
|
||||
|
||||
<dependencyManagement>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson</groupId>
|
||||
<artifactId>jackson-bom</artifactId>
|
||||
<version>${jackson2.version}</version>
|
||||
<type>pom</type>
|
||||
<scope>import</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</dependencyManagement>
|
||||
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>tools.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
<version>${jackson3.version}</version>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.core</groupId>
|
||||
<artifactId>jackson-databind</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>com.fasterxml.jackson.datatype</groupId>
|
||||
<artifactId>jackson-datatype-jsr310</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
Executable
+17
@@ -0,0 +1,17 @@
|
||||
#!/usr/bin/env bash
|
||||
# Compiles each file in src/broken/ against Jackson 3 and records the compiler's own message.
|
||||
# Output keeps each "error:" line with its source line and caret, and the error count (javac lists every candidate overload).
|
||||
# These files are deliberately NOT part of the Maven build (they live outside src/main).
|
||||
set -uo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
CP="target/classes:$(cat target/cp.txt)"
|
||||
OUT=output/Broken-compile-errors.txt
|
||||
: > "$OUT"
|
||||
for f in src/broken/*.java; do
|
||||
echo "=== $(basename "$f") ===" >> "$OUT"
|
||||
tmp=$(mktemp -d)
|
||||
javac -Xlint:none -d "$tmp" -cp "$CP" "$f" 2>&1 | grep -vE "Picked up|^Note:" | sed "s#^src/broken/##" | awk '/error:/{c=3} c>0{print; c--} /^[0-9]+ errors?$/{print}' >> "$OUT"
|
||||
rm -rf "$tmp"
|
||||
echo >> "$OUT"
|
||||
done
|
||||
echo "wrote $OUT ($(wc -l < "$OUT") lines)"
|
||||
Executable
+15
@@ -0,0 +1,15 @@
|
||||
#!/usr/bin/env bash
|
||||
# Regenerates every file in output/. Run from the module directory: ./scripts/run-all.sh
|
||||
# Needs JDK 25 and Maven. Timing lines in P07 are indicative and drift between runs.
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/.."
|
||||
mvn -B -q compile 2>&1 | grep -vE "Picked up|WARNING" || true
|
||||
mvn -B -q dependency:build-classpath -Dmdep.outputFile=target/cp.txt >/dev/null 2>&1
|
||||
CP="target/classes:$(cat target/cp.txt)"
|
||||
mkdir -p output
|
||||
for c in P01TwoMappersSideBySide P02ImmutableMapper P03ReadWriteCookbook P04ConfigRecipes \
|
||||
P05JavaTime P06Exceptions P07SharedMapperThreads; do
|
||||
java -cp "$CP" "com.ankurm.objectmapper.$c" 2>&1 | grep -vE "Picked up|^WARNING" > "output/$c.txt"
|
||||
echo "ran $c ($(wc -l < output/$c.txt) lines)"
|
||||
done
|
||||
./scripts/broken.sh
|
||||
@@ -0,0 +1,13 @@
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
import tools.jackson.databind.SerializationFeature;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/** Jackson 2 habit: build a mapper, then configure it. On Jackson 3 none of these methods exist. */
|
||||
public class Broken1MutateAfterBuild {
|
||||
public static void main(String[] args) {
|
||||
JsonMapper mapper = JsonMapper.builder().build();
|
||||
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
|
||||
mapper.configure(SerializationFeature.INDENT_OUTPUT, true);
|
||||
mapper.enable(SerializationFeature.INDENT_OUTPUT);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/** Jackson 2 allowed readValue(URL, Class). Jackson 3 has no URL overload. */
|
||||
public class Broken2ReadValueUrl {
|
||||
public static void main(String[] args) throws Exception {
|
||||
JsonMapper mapper = JsonMapper.builder().build();
|
||||
Object o = mapper.readValue(new java.net.URL("https://example.com/a.json"), Object.class);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import java.io.IOException;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/** Jackson 2 habit: wrap the mapper in try/catch (IOException). Jackson 3 throws nothing checked. */
|
||||
public class Broken3CatchIOException {
|
||||
public static void main(String[] args) {
|
||||
JsonMapper mapper = JsonMapper.builder().build();
|
||||
try {
|
||||
mapper.readValue("{}", Object.class);
|
||||
} catch (IOException e) {
|
||||
System.out.println("never reached");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
import tools.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/** There is no JavaTimeModule under tools.jackson: java.time support is built into jackson-databind 3. */
|
||||
public class Broken4JavaTimeModule {
|
||||
public static void main(String[] args) {
|
||||
JsonMapper mapper = JsonMapper.builder().addModule(new JavaTimeModule()).build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import tools.jackson.databind.SerializationFeature;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/** WRITE_DATES_AS_TIMESTAMPS moved from SerializationFeature to DateTimeFeature in Jackson 3. */
|
||||
public class Broken5WriteDatesAsTimestamps {
|
||||
public static void main(String[] args) {
|
||||
JsonMapper mapper = JsonMapper.builder()
|
||||
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS).build();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package com.ankurm.objectmapper;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* The plain POJO used by every example in this module. It carries NO Jackson annotations,
|
||||
* so the same class is read and written by Jackson 2 and Jackson 3 without any change.
|
||||
*/
|
||||
public class Article {
|
||||
private Long articleId;
|
||||
private String title;
|
||||
private List<String> tags;
|
||||
private String subtitle; // left null on purpose in most examples
|
||||
|
||||
public Article() { } // Jackson needs a no-arg constructor for a bean like this
|
||||
|
||||
public Article(Long articleId, String title, List<String> tags) {
|
||||
this.articleId = articleId;
|
||||
this.title = title;
|
||||
this.tags = tags;
|
||||
}
|
||||
|
||||
public Long getArticleId() { return articleId; }
|
||||
public void setArticleId(Long articleId) { this.articleId = articleId; }
|
||||
public String getTitle() { return title; }
|
||||
public void setTitle(String title) { this.title = title; }
|
||||
public List<String> getTags() { return tags; }
|
||||
public void setTags(List<String> tags) { this.tags = tags; }
|
||||
public String getSubtitle() { return subtitle; }
|
||||
public void setSubtitle(String subtitle) { this.subtitle = subtitle; }
|
||||
}
|
||||
+45
@@ -0,0 +1,45 @@
|
||||
package com.ankurm.objectmapper;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** The same write + read with Jackson 2's ObjectMapper and Jackson 3's JsonMapper. */
|
||||
public class P01TwoMappersSideBySide {
|
||||
public static void main(String[] args) throws Exception {
|
||||
Article article = new Article(1L, "Jackson Deep Dive", List.of("java", "json"));
|
||||
|
||||
// ---- Jackson 2: package com.fasterxml.jackson.databind ----
|
||||
com.fasterxml.jackson.databind.ObjectMapper m2 = new com.fasterxml.jackson.databind.ObjectMapper();
|
||||
String json2 = m2.writeValueAsString(article);
|
||||
|
||||
// ---- Jackson 3: package tools.jackson.databind.json ----
|
||||
tools.jackson.databind.json.JsonMapper m3 = tools.jackson.databind.json.JsonMapper.builder().build();
|
||||
String json3 = m3.writeValueAsString(article);
|
||||
|
||||
System.out.println("Jackson 2 " + m2.version() + " -> " + json2);
|
||||
System.out.println("Jackson 3 " + m3.version() + " -> " + json3);
|
||||
System.out.println("identical JSON: " + json2.equals(json3));
|
||||
System.out.println();
|
||||
|
||||
// Reading back is the same call in both.
|
||||
Article back2 = m2.readValue(json2, Article.class);
|
||||
Article back3 = m3.readValue(json3, Article.class);
|
||||
System.out.println("Jackson 2 read title: " + back2.getTitle());
|
||||
System.out.println("Jackson 3 read title: " + back3.getTitle());
|
||||
System.out.println();
|
||||
|
||||
// Pretty printing: Jackson 3 takes the feature on the builder, or per call on a writer.
|
||||
String pretty3 = m3.writerWithDefaultPrettyPrinter().writeValueAsString(article);
|
||||
System.out.println(pretty3);
|
||||
System.out.println();
|
||||
|
||||
// Which classes are these, really?
|
||||
System.out.println("m2 class: " + m2.getClass().getName());
|
||||
System.out.println("m3 class: " + m3.getClass().getName());
|
||||
System.out.println("m3 superclass: " + m3.getClass().getSuperclass().getName());
|
||||
System.out.println("m3 is-a tools.jackson.databind.ObjectMapper: "
|
||||
+ (m3 instanceof tools.jackson.databind.ObjectMapper));
|
||||
// The annotation package is shared between the two majors.
|
||||
System.out.println("@JsonInclude lives in: "
|
||||
+ com.fasterxml.jackson.annotation.JsonInclude.class.getPackageName());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
package com.ankurm.objectmapper;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.TreeSet;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
|
||||
/** Why Jackson 3 removed the setters: configuring a Jackson 2 mapper after first use is unreliable. */
|
||||
public class P02ImmutableMapper {
|
||||
|
||||
private static List<String> mutators(Class<?> c) {
|
||||
return new TreeSet<>(Arrays.stream(c.getMethods())
|
||||
.map(Method::getName)
|
||||
.filter(n -> n.startsWith("set") || n.equals("configure") || n.equals("enable")
|
||||
|| n.equals("disable") || n.startsWith("register") || n.equals("addMixIn")
|
||||
|| n.startsWith("activateDefaultTyping") || n.equals("findAndRegisterModules"))
|
||||
.toList()).stream().toList();
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
System.out.println("== public mutator methods on the mapper class ==");
|
||||
System.out.println("Jackson 2 ObjectMapper : "
|
||||
+ mutators(com.fasterxml.jackson.databind.ObjectMapper.class).size() + " distinct names");
|
||||
System.out.println("Jackson 3 ObjectMapper : "
|
||||
+ mutators(tools.jackson.databind.ObjectMapper.class).size() + " distinct names");
|
||||
System.out.println("Jackson 3 JsonMapper : "
|
||||
+ mutators(tools.jackson.databind.json.JsonMapper.class).size() + " distinct names");
|
||||
System.out.println(" the one Jackson 3 name that matched: " + mutators(tools.jackson.databind.ObjectMapper.class)
|
||||
+ " (a getter, not a setter)");
|
||||
System.out.println();
|
||||
|
||||
Article withNull = new Article(1L, "Jackson Deep Dive", List.of("java")); // subtitle == null
|
||||
|
||||
// ---- Jackson 2: change the inclusion rule AFTER the mapper has already serialised an Article ----
|
||||
com.fasterxml.jackson.databind.ObjectMapper m2 = new com.fasterxml.jackson.databind.ObjectMapper();
|
||||
System.out.println("== Jackson 2: reconfigure after first use ==");
|
||||
System.out.println("before : " + m2.writeValueAsString(withNull));
|
||||
m2.setSerializationInclusion(JsonInclude.Include.NON_NULL);
|
||||
System.out.println("after setSerializationInclusion(NON_NULL) : " + m2.writeValueAsString(withNull));
|
||||
com.fasterxml.jackson.databind.ObjectMapper fresh2 = new com.fasterxml.jackson.databind.ObjectMapper();
|
||||
fresh2.setSerializationInclusion(JsonInclude.Include.NON_NULL);
|
||||
System.out.println("fresh mapper, same setting : " + fresh2.writeValueAsString(withNull));
|
||||
System.out.println();
|
||||
|
||||
// ---- Jackson 3: the mapper is final-config; derive a new one with rebuild() ----
|
||||
tools.jackson.databind.json.JsonMapper m3 = tools.jackson.databind.json.JsonMapper.builder().build();
|
||||
System.out.println("== Jackson 3: rebuild() derives a new mapper ==");
|
||||
System.out.println("original : " + m3.writeValueAsString(withNull));
|
||||
tools.jackson.databind.json.JsonMapper nonNull = m3.rebuild()
|
||||
.changeDefaultPropertyInclusion(i -> i.withValueInclusion(JsonInclude.Include.NON_NULL))
|
||||
.build();
|
||||
System.out.println("rebuilt NON_NULL : " + nonNull.writeValueAsString(withNull));
|
||||
System.out.println("original again : " + m3.writeValueAsString(withNull));
|
||||
System.out.println("same instance? : " + (m3 == nonNull));
|
||||
}
|
||||
}
|
||||
+103
@@ -0,0 +1,103 @@
|
||||
package com.ankurm.objectmapper;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.StringReader;
|
||||
import java.lang.reflect.Method;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import tools.jackson.core.type.TypeReference;
|
||||
import tools.jackson.databind.JsonNode;
|
||||
import tools.jackson.databind.ObjectReader;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/** Every way in and out, on Jackson 3. One mapper, built once. */
|
||||
public class P03ReadWriteCookbook {
|
||||
public static void main(String[] args) throws Exception {
|
||||
JsonMapper mapper = JsonMapper.builder().build();
|
||||
Article article = new Article(1L, "Jackson Deep Dive", List.of("java", "json"));
|
||||
|
||||
// ---- WRITE ----
|
||||
String asString = mapper.writeValueAsString(article);
|
||||
byte[] asBytes = mapper.writeValueAsBytes(article);
|
||||
Path file = Files.createTempFile("article", ".json");
|
||||
mapper.writeValue(file, article); // Path (java.nio)
|
||||
mapper.writeValue(file.toFile(), article); // File
|
||||
ByteArrayOutputStream out = new ByteArrayOutputStream();
|
||||
mapper.writeValue(out, article); // OutputStream
|
||||
System.out.println("writeValueAsString : " + asString);
|
||||
System.out.println("writeValueAsBytes : " + asBytes.length + " bytes");
|
||||
System.out.println("writeValue(Path) : " + Files.readString(file));
|
||||
System.out.println("writeValue(Stream) : " + out.size() + " bytes");
|
||||
System.out.println();
|
||||
|
||||
// ---- READ ----
|
||||
System.out.println("read String : " + mapper.readValue(asString, Article.class).getTitle());
|
||||
System.out.println("read byte[] : " + mapper.readValue(asBytes, Article.class).getTitle());
|
||||
System.out.println("read File : " + mapper.readValue(file.toFile(), Article.class).getTitle());
|
||||
System.out.println("read Path : " + mapper.readValue(file, Article.class).getTitle());
|
||||
System.out.println("read InputStream : "
|
||||
+ mapper.readValue(new ByteArrayInputStream(asBytes), Article.class).getTitle());
|
||||
System.out.println("read Reader : "
|
||||
+ mapper.readValue(new StringReader(asString), Article.class).getTitle());
|
||||
Files.delete(file);
|
||||
System.out.println();
|
||||
|
||||
// ---- GENERIC TYPES: a Class<T> cannot carry List<Article>, a TypeReference can ----
|
||||
String array = "[{\"articleId\":1,\"title\":\"First\"},{\"articleId\":2,\"title\":\"Second\"}]";
|
||||
List<Article> list = mapper.readValue(array, new TypeReference<List<Article>>() { });
|
||||
System.out.println("List<Article> size : " + list.size() + ", element class: " + list.get(0).getClass().getSimpleName());
|
||||
List<?> raw = mapper.readValue(array, List.class);
|
||||
System.out.println("List.class element : " + raw.get(0).getClass().getName());
|
||||
System.out.println();
|
||||
|
||||
// ---- TREE and convertValue ----
|
||||
JsonNode tree = mapper.readTree(asString);
|
||||
System.out.println("tree title : " + tree.get("title").asString());
|
||||
System.out.println("tree tags[1] : " + tree.get("tags").get(1).asString());
|
||||
Map<String, Object> asMap = mapper.convertValue(article, new TypeReference<Map<String, Object>>() { });
|
||||
System.out.println("convertValue to Map : " + asMap);
|
||||
Article fromMap = mapper.convertValue(Map.of("articleId", 9, "title", "From a Map"), Article.class);
|
||||
System.out.println("convertValue to bean : " + fromMap.getArticleId() + " / " + fromMap.getTitle());
|
||||
System.out.println();
|
||||
|
||||
// ---- Reusable reader / writer: cheap, thread-safe, fixed to one type ----
|
||||
ObjectReader articleReader = mapper.readerFor(Article.class);
|
||||
Article viaReader = articleReader.readValue(asString);
|
||||
System.out.println("readerFor(Article) : " + viaReader.getTitle());
|
||||
System.out.println("pretty writer : "
|
||||
+ mapper.writerWithDefaultPrettyPrinter().writeValueAsString(Map.of("k", 1)).replace("\n", "\\n"));
|
||||
System.out.println();
|
||||
|
||||
// ---- Is there a readValue(URL) in each major? ----
|
||||
System.out.println("Jackson 2 readValue(URL, Class) exists : " + hasUrlOverload(
|
||||
com.fasterxml.jackson.databind.ObjectMapper.class));
|
||||
System.out.println("Jackson 3 readValue(URL, Class) exists : " + hasUrlOverload(
|
||||
tools.jackson.databind.ObjectMapper.class));
|
||||
System.out.println("Jackson 3 readTree(URL) exists : " + Arrays.stream(
|
||||
tools.jackson.databind.ObjectMapper.class.getMethods())
|
||||
.filter(m -> m.getName().equals("readTree"))
|
||||
.anyMatch(m -> m.getParameterCount() == 1 && m.getParameterTypes()[0] == java.net.URL.class));
|
||||
String marathi = "\u092e\u0930\u093e\u0920\u0940"; // five Devanagari code points
|
||||
byte[] utf8 = mapper.writeValueAsBytes(new Article(2L, marathi, null));
|
||||
System.out.println("non-ASCII byte[] round trip equal : "
|
||||
+ mapper.readValue(utf8, Article.class).getTitle().equals(marathi)
|
||||
+ " (bytes are " + StandardCharsets.UTF_8.name() + " by default: "
|
||||
+ new String(utf8, StandardCharsets.UTF_8).contains(marathi) + ")");
|
||||
}
|
||||
|
||||
private static boolean hasUrlOverload(Class<?> mapperClass) {
|
||||
for (Method m : mapperClass.getMethods()) {
|
||||
if (m.getName().equals("readValue") && m.getParameterCount() == 2
|
||||
&& m.getParameterTypes()[0] == java.net.URL.class) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,93 @@
|
||||
package com.ankurm.objectmapper;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude;
|
||||
|
||||
import tools.jackson.databind.DeserializationFeature;
|
||||
import tools.jackson.databind.PropertyNamingStrategies;
|
||||
import tools.jackson.databind.SerializationFeature;
|
||||
import tools.jackson.databind.cfg.DateTimeFeature;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/** The configuration most projects actually need, and what the two majors default to. */
|
||||
public class P04ConfigRecipes {
|
||||
public static void main(String[] args) throws Exception {
|
||||
// ---- 1. Defaults, read from the enums themselves (nothing typed by hand) ----
|
||||
System.out.println("== default value of a few features (enabledByDefault) ==");
|
||||
System.out.printf("%-52s %-8s %-8s%n", "feature", "Jackson2", "Jackson3");
|
||||
row("DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES",
|
||||
com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault(),
|
||||
DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES.enabledByDefault());
|
||||
row("SerializationFeature.FAIL_ON_EMPTY_BEANS",
|
||||
com.fasterxml.jackson.databind.SerializationFeature.FAIL_ON_EMPTY_BEANS.enabledByDefault(),
|
||||
SerializationFeature.FAIL_ON_EMPTY_BEANS.enabledByDefault());
|
||||
row("SerializationFeature.INDENT_OUTPUT",
|
||||
com.fasterxml.jackson.databind.SerializationFeature.INDENT_OUTPUT.enabledByDefault(),
|
||||
SerializationFeature.INDENT_OUTPUT.enabledByDefault());
|
||||
row("WRITE_DATES_AS_TIMESTAMPS (J2: SerializationFeature, J3: DateTimeFeature)",
|
||||
com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS.enabledByDefault(),
|
||||
DateTimeFeature.WRITE_DATES_AS_TIMESTAMPS.enabledByDefault());
|
||||
row("DeserializationFeature.FAIL_ON_TRAILING_TOKENS",
|
||||
com.fasterxml.jackson.databind.DeserializationFeature.FAIL_ON_TRAILING_TOKENS.enabledByDefault(),
|
||||
DeserializationFeature.FAIL_ON_TRAILING_TOKENS.enabledByDefault());
|
||||
row("MapperFeature.SORT_PROPERTIES_ALPHABETICALLY",
|
||||
com.fasterxml.jackson.databind.MapperFeature.SORT_PROPERTIES_ALPHABETICALLY.enabledByDefault(),
|
||||
tools.jackson.databind.MapperFeature.SORT_PROPERTIES_ALPHABETICALLY.enabledByDefault());
|
||||
System.out.println();
|
||||
|
||||
// ---- 2. The behaviour behind the first row ----
|
||||
String withExtra = "{\"articleId\":1,\"title\":\"T\",\"views\":42}"; // 'views' is not on Article
|
||||
try {
|
||||
new com.fasterxml.jackson.databind.ObjectMapper().readValue(withExtra, Article.class);
|
||||
System.out.println("Jackson 2 default : accepted unknown field");
|
||||
} catch (Exception e) {
|
||||
System.out.println("Jackson 2 default : " + e.getClass().getSimpleName());
|
||||
}
|
||||
Article ok = JsonMapper.builder().build().readValue(withExtra, Article.class);
|
||||
System.out.println("Jackson 3 default : accepted unknown field, title=" + ok.getTitle());
|
||||
try {
|
||||
JsonMapper.builder().enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES).build()
|
||||
.readValue(withExtra, Article.class);
|
||||
} catch (Exception e) {
|
||||
System.out.println("Jackson 3 strict : " + e.getClass().getSimpleName());
|
||||
}
|
||||
try {
|
||||
JsonMapper.builderWithJackson2Defaults().build().readValue(withExtra, Article.class);
|
||||
System.out.println("builderWithJackson2Defaults : accepted unknown field");
|
||||
} catch (Exception e) {
|
||||
System.out.println("builderWithJackson2Defaults : " + e.getClass().getSimpleName() + " (Jackson 2 behaviour back)");
|
||||
}
|
||||
System.out.println();
|
||||
|
||||
// ---- 2b. Property order: Jackson 3 sorts alphabetically by default, Jackson 2 follows the class ----
|
||||
Article ordered = new Article(1L, "T", List.of("a"));
|
||||
ordered.setSubtitle("S");
|
||||
System.out.println("order J2 default : "
|
||||
+ new com.fasterxml.jackson.databind.ObjectMapper().writeValueAsString(ordered));
|
||||
System.out.println("order J3 default : " + JsonMapper.builder().build().writeValueAsString(ordered));
|
||||
System.out.println("order J3 sorting disabled : " + JsonMapper.builder()
|
||||
.disable(tools.jackson.databind.MapperFeature.SORT_PROPERTIES_ALPHABETICALLY).build()
|
||||
.writeValueAsString(ordered));
|
||||
System.out.println("order J3 Jackson2Defaults : "
|
||||
+ JsonMapper.builderWithJackson2Defaults().build().writeValueAsString(ordered));
|
||||
System.out.println();
|
||||
|
||||
// ---- 3. The recipe: one shared, immutable mapper for an application ----
|
||||
JsonMapper mapper = JsonMapper.builder()
|
||||
.enable(SerializationFeature.INDENT_OUTPUT) // pretty output
|
||||
.propertyNamingStrategy(PropertyNamingStrategies.SNAKE_CASE) // articleId -> article_id
|
||||
.changeDefaultPropertyInclusion(
|
||||
i -> i.withValueInclusion(JsonInclude.Include.NON_NULL)) // skip nulls
|
||||
.build();
|
||||
Article article = new Article(1L, "Jackson Deep Dive", List.of("java", "json")); // subtitle is null
|
||||
String json = mapper.writeValueAsString(article);
|
||||
System.out.println(json);
|
||||
Article back = mapper.readValue(json, Article.class);
|
||||
System.out.println("round trip articleId = " + back.getArticleId());
|
||||
}
|
||||
|
||||
private static void row(String name, boolean j2, boolean j3) {
|
||||
System.out.printf("%-52s %-8s %-8s%n", name, j2, j3);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package com.ankurm.objectmapper;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.util.Map;
|
||||
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/** java.time: an extra module and a flag in Jackson 2, nothing at all in Jackson 3. */
|
||||
public class P05JavaTime {
|
||||
public static void main(String[] args) throws Exception {
|
||||
Map<String, Object> payload = new java.util.LinkedHashMap<>();
|
||||
payload.put("published", LocalDate.of(2026, 11, 17));
|
||||
payload.put("at", Instant.parse("2026-11-17T00:47:00Z"));
|
||||
|
||||
// Jackson 2, plain mapper: java.time is rejected outright (since 2.12).
|
||||
com.fasterxml.jackson.databind.ObjectMapper plain2 = new com.fasterxml.jackson.databind.ObjectMapper();
|
||||
try {
|
||||
plain2.writeValueAsString(payload);
|
||||
} catch (Exception e) {
|
||||
System.out.println("Jackson 2, no module : " + e.getClass().getSimpleName());
|
||||
System.out.println(" " + e.getMessage().lines().findFirst().orElse(""));
|
||||
}
|
||||
|
||||
// Jackson 2 with the module: dates become number ARRAYS and a timestamp unless you also flip a flag.
|
||||
com.fasterxml.jackson.databind.ObjectMapper module2 = new com.fasterxml.jackson.databind.ObjectMapper()
|
||||
.registerModule(new JavaTimeModule());
|
||||
System.out.println("Jackson 2 + JavaTimeModule : " + module2.writeValueAsString(payload));
|
||||
|
||||
com.fasterxml.jackson.databind.ObjectMapper fixed2 = new com.fasterxml.jackson.databind.ObjectMapper()
|
||||
.registerModule(new JavaTimeModule())
|
||||
.disable(com.fasterxml.jackson.databind.SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
|
||||
System.out.println("Jackson 2 + module + disable(TIMESTAMPS): " + fixed2.writeValueAsString(payload));
|
||||
|
||||
// Jackson 3: no module, no flag.
|
||||
JsonMapper m3 = JsonMapper.builder().build();
|
||||
System.out.println("Jackson 3, plain JsonMapper : " + m3.writeValueAsString(payload));
|
||||
|
||||
// And it reads back.
|
||||
LocalDate back = m3.readValue("\"2026-11-17\"", LocalDate.class);
|
||||
System.out.println("Jackson 3 read LocalDate : " + back);
|
||||
|
||||
// Does the module still exist for Jackson 3?
|
||||
for (String cls : new String[] {
|
||||
"tools.jackson.datatype.jsr310.JavaTimeModule",
|
||||
"com.fasterxml.jackson.datatype.jsr310.JavaTimeModule"}) {
|
||||
try {
|
||||
Class.forName(cls);
|
||||
System.out.println("class present on classpath : " + cls);
|
||||
} catch (ClassNotFoundException e) {
|
||||
System.out.println("class NOT on classpath : " + cls);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
package com.ankurm.objectmapper;
|
||||
|
||||
import tools.jackson.core.JacksonException;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/** Checked in Jackson 2, unchecked in Jackson 3. Same malformed input, both mappers. */
|
||||
public class P06Exceptions {
|
||||
public static void main(String[] args) {
|
||||
String malformed = "{\"articleId\": 1, \"title\": }";
|
||||
String wrongType = "{\"articleId\": \"not-a-number\"}";
|
||||
|
||||
com.fasterxml.jackson.databind.ObjectMapper m2 = new com.fasterxml.jackson.databind.ObjectMapper();
|
||||
JsonMapper m3 = JsonMapper.builder().build();
|
||||
|
||||
System.out.println("== class hierarchy ==");
|
||||
System.out.println("J2 JsonProcessingException extends " + com.fasterxml.jackson.core.JsonProcessingException.class
|
||||
.getSuperclass().getName() + " -> extends "
|
||||
+ com.fasterxml.jackson.core.JsonProcessingException.class.getSuperclass().getSuperclass().getName());
|
||||
System.out.println("J3 JacksonException extends " + JacksonException.class.getSuperclass().getName());
|
||||
System.out.println();
|
||||
|
||||
System.out.println("== malformed JSON ==");
|
||||
try {
|
||||
m2.readValue(malformed, Article.class);
|
||||
} catch (com.fasterxml.jackson.core.JsonProcessingException e) { // checked: the compiler forces this catch
|
||||
System.out.println("J2 " + e.getClass().getName());
|
||||
System.out.println(" " + e.getOriginalMessage());
|
||||
System.out.println(" at line " + e.getLocation().getLineNr() + ", column " + e.getLocation().getColumnNr());
|
||||
}
|
||||
try {
|
||||
m3.readValue(malformed, Article.class); // no throws clause needed on main()
|
||||
} catch (JacksonException e) {
|
||||
System.out.println("J3 " + e.getClass().getName());
|
||||
System.out.println(" " + e.getOriginalMessage());
|
||||
System.out.println(" at line " + e.getLocation().getLineNr() + ", column " + e.getLocation().getColumnNr());
|
||||
}
|
||||
System.out.println();
|
||||
|
||||
System.out.println("== wrong value type ==");
|
||||
try {
|
||||
m2.readValue(wrongType, Article.class);
|
||||
} catch (com.fasterxml.jackson.core.JsonProcessingException e) {
|
||||
System.out.println("J2 " + e.getClass().getSimpleName());
|
||||
}
|
||||
try {
|
||||
m3.readValue(wrongType, Article.class);
|
||||
} catch (JacksonException e) {
|
||||
System.out.println("J3 " + e.getClass().getSimpleName() + " (path: "
|
||||
+ e.getPath().stream().map(r -> r.getPropertyName()).toList() + ")");
|
||||
}
|
||||
System.out.println();
|
||||
|
||||
// The whole point: a lambda body may now call the mapper with no try/catch.
|
||||
java.util.List<Article> parsed = java.util.stream.Stream.of(
|
||||
"{\"articleId\":1,\"title\":\"a\"}", "{\"articleId\":2,\"title\":\"b\"}")
|
||||
.map(s -> m3.readValue(s, Article.class)) // does not compile on Jackson 2
|
||||
.toList();
|
||||
System.out.println("stream + lambda parsed " + parsed.size() + " articles with no try/catch");
|
||||
}
|
||||
}
|
||||
+63
@@ -0,0 +1,63 @@
|
||||
package com.ankurm.objectmapper;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.concurrent.atomic.AtomicInteger;
|
||||
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/** One shared mapper across threads, versus building a mapper for every call. Timings are indicative. */
|
||||
public class P07SharedMapperThreads {
|
||||
static final int THREADS = 8;
|
||||
static final int PER_THREAD = 20_000;
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
JsonMapper shared = JsonMapper.builder().build();
|
||||
Article article = new Article(1L, "Jackson Deep Dive", List.of("java", "json"));
|
||||
String json = shared.writeValueAsString(article);
|
||||
|
||||
// ---- correctness: many threads, one mapper ----
|
||||
AtomicInteger wrong = new AtomicInteger();
|
||||
runThreads(() -> {
|
||||
for (int i = 0; i < PER_THREAD; i++) {
|
||||
Article a = shared.readValue(json, Article.class);
|
||||
if (!"Jackson Deep Dive".equals(a.getTitle()) || !shared.writeValueAsString(a).equals(json)) {
|
||||
wrong.incrementAndGet();
|
||||
}
|
||||
}
|
||||
});
|
||||
System.out.println(THREADS + " threads x " + PER_THREAD + " round trips on ONE JsonMapper, wrong results: " + wrong.get());
|
||||
System.out.println();
|
||||
|
||||
// ---- cost: shared mapper vs a new mapper per call (single thread, warm JVM) ----
|
||||
int n = 2_000;
|
||||
for (int round = 1; round <= 3; round++) { // three rounds so the JIT settles; read the last
|
||||
long t0 = System.nanoTime();
|
||||
for (int i = 0; i < n; i++) {
|
||||
shared.readValue(json, Article.class);
|
||||
}
|
||||
long sharedMs = (System.nanoTime() - t0) / 1_000_000;
|
||||
|
||||
t0 = System.nanoTime();
|
||||
for (int i = 0; i < n; i++) {
|
||||
JsonMapper.builder().build().readValue(json, Article.class);
|
||||
}
|
||||
long perCallMs = (System.nanoTime() - t0) / 1_000_000;
|
||||
System.out.println("round " + round + ": shared " + sharedMs + " ms, new mapper per call " + perCallMs
|
||||
+ " ms (" + n + " reads each)");
|
||||
}
|
||||
}
|
||||
|
||||
private static void runThreads(ThrowingRunnable body) throws Exception {
|
||||
List<Thread> threads = new ArrayList<>();
|
||||
for (int t = 0; t < THREADS; t++) {
|
||||
Thread th = Thread.ofPlatform().start(() -> {
|
||||
try { body.run(); } catch (Exception e) { throw new RuntimeException(e); }
|
||||
});
|
||||
threads.add(th);
|
||||
}
|
||||
for (Thread th : threads) { th.join(); }
|
||||
}
|
||||
|
||||
interface ThrowingRunnable { void run() throws Exception; }
|
||||
}
|
||||
Reference in New Issue
Block a user