Core Jackson processing abstractions (aka Streaming API), implementation for JSON
—
Jackson Core provides a comprehensive exception hierarchy for handling JSON processing errors with detailed location information and specific error types for different failure scenarios.
public abstract class JacksonException extends IOException {
protected JacksonException(String msg);
protected JacksonException(String msg, Throwable rootCause);
public abstract JsonLocation getLocation();
public abstract String getOriginalMessage();
public abstract Object getProcessor();
public String getMessageSuffix();
public String getMessage();
}
public abstract class JsonProcessingException extends JacksonException {
protected JsonProcessingException(String msg);
protected JsonProcessingException(String msg, JsonLocation loc);
protected JsonProcessingException(String msg, Throwable rootCause);
protected JsonProcessingException(String msg, JsonLocation loc, Throwable rootCause);
@Override
public JsonLocation getLocation();
public void clearLocation();
@Override
public String getOriginalMessage();
public String getMessageSuffix();
protected String _buildMessage();
}public class JsonParseException extends JsonProcessingException {
public JsonParseException(JsonParser p, String msg);
public JsonParseException(JsonParser p, String msg, Throwable rootCause);
public JsonParseException(JsonParser p, String msg, JsonLocation loc);
public JsonParseException(JsonParser p, String msg, JsonLocation loc, Throwable rootCause);
@Override
public JsonParser getProcessor();
public RequestPayload getRequestPayload();
public JsonParseException withRequestPayload(RequestPayload p);
}public class JsonGenerationException extends JsonProcessingException {
public JsonGenerationException(Throwable rootCause);
public JsonGenerationException(String msg);
public JsonGenerationException(String msg, Throwable rootCause);
public JsonGenerationException(Throwable rootCause, JsonGenerator g);
public JsonGenerationException(String msg, JsonGenerator g);
public JsonGenerationException(String msg, Throwable rootCause, JsonGenerator g);
@Override
public JsonGenerator getProcessor();
}public class StreamReadException extends JsonProcessingException {
public StreamReadException(JsonParser p, String msg);
public StreamReadException(JsonParser p, String msg, Throwable rootCause);
public StreamReadException(JsonParser p, String msg, JsonLocation loc);
public StreamReadException(JsonParser p, String msg, JsonLocation loc, Throwable rootCause);
@Override
public JsonParser getProcessor();
public RequestPayload getRequestPayload();
public StreamReadException withRequestPayload(RequestPayload p);
}
public class InputCoercionException extends StreamReadException {
protected final Class<?> _targetType;
public InputCoercionException(JsonParser p, String msg, JsonToken inputType, Class<?> targetType);
public InputCoercionException(JsonParser p, String msg, JsonLocation loc, JsonToken inputType, Class<?> targetType);
public Class<?> getTargetType();
public JsonToken getInputType();
}
public class StreamConstraintsException extends StreamReadException {
public StreamConstraintsException(String msg);
public StreamConstraintsException(String msg, JsonLocation loc);
}public class StreamWriteException extends JsonProcessingException {
public StreamWriteException(Throwable rootCause);
public StreamWriteException(String msg);
public StreamWriteException(String msg, Throwable rootCause);
public StreamWriteException(Throwable rootCause, JsonGenerator g);
public StreamWriteException(String msg, JsonGenerator g);
public StreamWriteException(String msg, Throwable rootCause, JsonGenerator g);
@Override
public JsonGenerator getProcessor();
}public class JsonEOFException extends JsonParseException {
public JsonEOFException(JsonParser p, JsonToken token, String msg);
public JsonToken getTokenBeingDecoded();
}public class JsonLocation implements Serializable {
public static final JsonLocation NA;
public JsonLocation(ContentReference contentRef, long totalChars, int lineNr, int colNr);
public JsonLocation(ContentReference contentRef, long totalChars, long totalBytes, int lineNr, int colNr);
public ContentReference contentReference();
public Object getSourceRef();
public int getLineNr();
public int getColumnNr();
public long getCharOffset();
public long getByteOffset();
public String sourceDescription();
public String offsetDescription();
@Override
public String toString();
public String buildSourceDescription();
public int hashCode();
public boolean equals(Object other);
}
public class ContentReference implements Serializable {
public static ContentReference rawReference(Object rawContent);
public static ContentReference rawReference(boolean redactContent, Object rawContent);
public static ContentReference construct(boolean redactContent, Object rawContent);
public static ContentReference unknown();
public Object getRawContent();
public boolean hasTextualContent();
public String buildSourceDescription();
public boolean equals(Object other);
public int hashCode();
}public class RequestPayload implements Serializable {
protected byte[] _payloadAsBytes;
protected CharSequence _payloadAsText;
public RequestPayload(byte[] bytes);
public RequestPayload(CharSequence str);
public Object getRawPayload();
public String toString();
}try {
JsonParser parser = factory.createParser(jsonInput);
while (parser.nextToken() != null) {
// Process tokens
}
parser.close();
} catch (JsonParseException e) {
System.err.println("Parse error at " + e.getLocation() + ": " + e.getOriginalMessage());
// Optional: Get request payload for debugging
RequestPayload payload = e.getRequestPayload();
if (payload != null) {
System.err.println("Input: " + payload.toString());
}
} catch (StreamReadException e) {
System.err.println("Stream read error: " + e.getMessage());
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
}try {
JsonGenerator generator = factory.createGenerator(outputStream);
generator.writeStartObject();
generator.writeStringField("key", value);
generator.writeEndObject();
generator.close();
} catch (JsonGenerationException e) {
System.err.println("Generation error: " + e.getOriginalMessage());
JsonGenerator processor = (JsonGenerator) e.getProcessor();
if (processor != null) {
System.err.println("Generator context: " + processor.getOutputContext());
}
} catch (StreamWriteException e) {
System.err.println("Stream write error: " + e.getMessage());
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
}try {
JsonFactory factory = JsonFactory.builder()
.streamReadConstraints(StreamReadConstraints.builder()
.maxStringLength(1000)
.maxNestingDepth(10)
.build())
.build();
JsonParser parser = factory.createParser(jsonInput);
// ... parsing
} catch (StreamConstraintsException e) {
System.err.println("Constraint violation: " + e.getMessage());
System.err.println("Location: " + e.getLocation());
} catch (JsonParseException e) {
System.err.println("Parse error: " + e.getMessage());
}try {
JsonParser parser = factory.createParser("{\"age\": \"not_a_number\"}");
parser.nextToken(); // START_OBJECT
parser.nextToken(); // FIELD_NAME
parser.nextToken(); // VALUE_STRING
int age = parser.getIntValue(); // This will throw InputCoercionException
} catch (InputCoercionException e) {
System.err.println("Cannot convert " + e.getInputType() +
" to " + e.getTargetType().getSimpleName());
System.err.println("Value: " + parser.getText());
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
}try {
// ... JSON processing
} catch (JsonProcessingException e) {
// Get location details
JsonLocation loc = e.getLocation();
if (loc != null) {
System.err.println("Error at line " + loc.getLineNr() +
", column " + loc.getColumnNr());
System.err.println("Character offset: " + loc.getCharOffset());
System.err.println("Source: " + loc.sourceDescription());
}
// Get original message without location decoration
String originalMsg = e.getOriginalMessage();
System.err.println("Original error: " + originalMsg);
// Get processor information
Object processor = e.getProcessor();
if (processor instanceof JsonParser) {
JsonParser p = (JsonParser) processor;
System.err.println("Parser state: " + p.getCurrentToken());
System.err.println("Current name: " + p.getCurrentName());
}
}public void parseJsonWithErrorReporting(String json) {
try {
JsonParser parser = factory.createParser(json);
// ... parsing logic
} catch (JsonParseException e) {
// Add request payload for better error reporting
RequestPayload payload = new RequestPayload(json);
JsonParseException enhancedException = e.withRequestPayload(payload);
logError("JSON parsing failed", enhancedException);
throw enhancedException;
}
}
private void logError(String message, JsonParseException e) {
logger.error("{}: {} at {}", message, e.getOriginalMessage(), e.getLocation());
RequestPayload payload = e.getRequestPayload();
if (payload != null) {
logger.debug("Input content: {}", payload.toString());
}
}try {
JsonParser parser = factory.createParser(incompleteJson);
while (parser.nextToken() != null) {
// Process tokens
}
} catch (JsonEOFException e) {
JsonToken expectedToken = e.getTokenBeingDecoded();
System.err.println("Unexpected end of input, expected: " + expectedToken);
System.err.println("At location: " + e.getLocation());
}public List<JsonNode> parseJsonArray(String jsonArray, boolean lenient) {
List<JsonNode> results = new ArrayList<>();
try {
JsonParser parser = factory.createParser(jsonArray);
parser.nextToken(); // START_ARRAY
while (parser.nextToken() != JsonToken.END_ARRAY) {
try {
JsonNode node = parser.readValueAsTree();
results.add(node);
} catch (JsonParseException e) {
if (lenient) {
logger.warn("Skipping invalid JSON element: " + e.getMessage());
parser.skipChildren(); // Skip malformed element
} else {
throw e;
}
}
}
} catch (IOException e) {
if (!lenient) {
throw new RuntimeException("JSON parsing failed", e);
}
logger.error("Failed to parse JSON array", e);
}
return results;
}Install with Tessl CLI
npx tessl i tessl/maven-com-fasterxml-jackson-core--jackson-core