Developer Documentation
Java
Updated September 19, 2026

Validate JSON in Java

Validate JSON syntax and handle parser errors without mutating the input in Java.

Syntax validation answers one question: can the input be parsed as JSON? It is different from JSON Schema validation, which checks the shape and constraints of already valid JSON data.

Quick Start#

The following example uses the standard Java API or a widely used package for this task.

Syntax validation with Jackson#

Java
1ObjectMapper mapper = new ObjectMapper();2try {3    JsonNode value = mapper.readTree(input);4    System.out.println("Valid JSON");5} catch (JsonProcessingException ex) {6    JsonLocation loc = ex.getLocation();7    System.out.printf("Invalid near line %d, column %d%n", loc.getLineNr(), loc.getColumnNr());8}

Common Operations#

This second pattern covers a common production operation or a safer way to handle real input.

Require a JSON object#

Java
1JsonNode value = mapper.readTree(input);2if (!value.isObject()) {3    throw new IllegalArgumentException("Expected a JSON object");4}5if (!value.hasNonNull("name") || !value.get("name").isTextual()) {6    throw new IllegalArgumentException("name must be a string");7}

Important Notes#

Parser exceptions can expose line and column information; preserve those details when building editor diagnostics.

Best Practices#

  1. Treat external input as untrusted and handle parse/validation errors explicitly.
  2. Keep encoding, units, formats, and library-specific mapping rules explicit at system boundaries.
  3. Add test vectors that cover empty input, Unicode text, malformed input, and representative production data.

References#

Implement JSON Validator in other languages: