Part 0: the same payload read by data binding, tree model and streaming
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
package com.ankurm.jackson3.part0setup;
|
||||
|
||||
import tools.jackson.core.JsonParser;
|
||||
import tools.jackson.core.JsonToken;
|
||||
import tools.jackson.databind.JsonNode;
|
||||
import tools.jackson.databind.json.JsonMapper;
|
||||
|
||||
/**
|
||||
* Post: Jackson 101 — https://ankurm.com/jackson-java-tutorial/
|
||||
* Section: "Jackson's Three Processing Models"
|
||||
*
|
||||
* The same payload read three ways, so the trade-off is concrete rather than a table.
|
||||
*/
|
||||
public class A03ThreeProcessingModels {
|
||||
|
||||
public record Order(Long orderId, String status) { }
|
||||
|
||||
private static final String JSON = "{\"orderId\":1001,\"status\":\"SHIPPED\"}";
|
||||
|
||||
public static void main(String[] args) {
|
||||
JsonMapper mapper = JsonMapper.builder().build();
|
||||
|
||||
// 1. DATA BINDING — the right answer roughly 95% of the time.
|
||||
Order bound = mapper.readValue(JSON, Order.class);
|
||||
System.out.println("1. data binding : " + bound);
|
||||
|
||||
// 2. TREE MODEL — schema not known at compile time; navigate a JsonNode.
|
||||
JsonNode tree = mapper.readTree(JSON);
|
||||
System.out.println("2. tree model : orderId=" + tree.path("orderId").asInt()
|
||||
+ " status=" + tree.path("status").asString());
|
||||
|
||||
// 3. STREAMING — token by token, constant memory, no document ever built.
|
||||
StringBuilder streamed = new StringBuilder();
|
||||
try (JsonParser parser = mapper.createParser(JSON)) {
|
||||
while (parser.nextToken() != null) {
|
||||
if (parser.currentToken() == JsonToken.PROPERTY_NAME) {
|
||||
String field = parser.currentName();
|
||||
parser.nextToken(); // advance to the value
|
||||
streamed.append(field).append('=').append(parser.getString()).append(' ');
|
||||
}
|
||||
}
|
||||
}
|
||||
System.out.println("3. streaming : " + streamed.toString().trim());
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user