Part 6: streaming parser filter with the Jackson 3 token/accessor names
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
package com.ankurm.jackson3.part6streaming;
|
||||
|
||||
import tools.jackson.core.JsonParser;
|
||||
import tools.jackson.core.JsonToken;
|
||||
import tools.jackson.core.json.JsonFactory;
|
||||
|
||||
import java.io.File;
|
||||
import java.nio.file.Files;
|
||||
|
||||
/**
|
||||
* Post: Streaming API and JsonNode — https://ankurm.com/jackson-streaming-api-jsonnode/
|
||||
* Section: "Reading a Large JSON Array with JsonParser"
|
||||
*
|
||||
* Jackson 3 differences from the post's code:
|
||||
* 1. JsonFactory is in tools.jackson.core.json — NOT tools.jackson.core.
|
||||
* 2. parser.getCurrentName() is now parser.currentName().
|
||||
* 3. parser.getText() is now parser.getString().
|
||||
* 4. JsonToken.FIELD_NAME is now JsonToken.PROPERTY_NAME.
|
||||
* 5. No `throws IOException` — Jackson 3 exceptions are unchecked.
|
||||
*/
|
||||
public class G01StreamingParserFilter {
|
||||
|
||||
private static final String SAMPLE = """
|
||||
[
|
||||
{"level":"INFO","message":"Application started"},
|
||||
{"level":"ERROR","message":"Database connection failed"},
|
||||
{"level":"INFO","message":"Retrying connection"}
|
||||
]
|
||||
""";
|
||||
|
||||
public static void main(String[] args) throws Exception {
|
||||
File logFile = File.createTempFile("large-logs", ".json");
|
||||
Files.writeString(logFile.toPath(), SAMPLE);
|
||||
logFile.deleteOnExit();
|
||||
|
||||
JsonFactory jsonFactory = new JsonFactory();
|
||||
int errorCount = 0;
|
||||
|
||||
try (JsonParser parser = jsonFactory.createParser(tools.jackson.core.ObjectReadContext.empty(), logFile)) {
|
||||
|
||||
// Confirm the root is an array
|
||||
if (parser.nextToken() != JsonToken.START_ARRAY) {
|
||||
throw new IllegalStateException("Expected a JSON array at the root");
|
||||
}
|
||||
|
||||
// Walk each element in the array
|
||||
while (parser.nextToken() != JsonToken.END_ARRAY) {
|
||||
|
||||
String logLevel = null;
|
||||
String logMessage = null;
|
||||
|
||||
// Walk each property inside the current object
|
||||
while (parser.nextToken() != JsonToken.END_OBJECT) {
|
||||
String fieldName = parser.currentName();
|
||||
parser.nextToken(); // move to the value
|
||||
|
||||
if ("level".equals(fieldName)) {
|
||||
logLevel = parser.getString();
|
||||
} else if ("message".equals(fieldName)) {
|
||||
logMessage = parser.getString();
|
||||
}
|
||||
// All other fields are skipped automatically
|
||||
}
|
||||
|
||||
if ("ERROR".equals(logLevel)) {
|
||||
System.out.println("ERROR: " + logMessage);
|
||||
errorCount++;
|
||||
}
|
||||
}
|
||||
}
|
||||
System.out.println("Total errors found: " + errorCount);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user