JSON Schema Validator — Java source
Validate a JSON document against a draft-07 subset schema: types, required, bounds, patterns, enums, arrays and strict objects, every issue reported at its exact path. Pairs with the schema generator. Runs locally with a shareable link.
This is the Java implementation — the same logic the interactive tool runs, in a shareable, citable form.
// json-schema-validator — draft-07 SUBSET JSON Schema validator. Java port
// (canonical TS: src/lib/json-schema-validator.ts; Go twin:
// cli/json-schema-validator). Validates a JSON instance against a schema
// supporting: type (string or array, "integer" counts as "number"), enum,
// const, minimum/maximum/exclusiveMinimum/exclusiveMaximum, minLength/
// maxLength (TS .length counts UTF-16 code units: astral chars are 2),
// pattern, minItems/maxItems, uniqueItems, items, required, properties,
// additionalProperties: false, and the boolean schemas true/false.
// Unsupported keywords ($ref/$defs, oneOf/anyOf/allOf/not, patternProperties,
// dependencies, format, propertyNames, contains) are ignored, exactly like
// the TS lib and the Go twin. The JDK ships no JSON parser, so this file
// carries a terse recursive-descent one building LinkedHashMap/ArrayList/
// String/Double/Boolean trees (LinkedHashMap keeps insertion order, so issue
// ordering matches the TS Object.keys walk); patterns run through
// java.util.regex. All JSON numbers become doubles flagged integral at
// validation time (Number.isInteger semantics for |v| <= 2^53). Numbers print
// into messages with JS Number-to-string rules via jsNum (70000, 1.5e-7,
// 1e+21). Never throws — errors travel in the Result.
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
public class JsonSchemaValidator {
public record Issue(String path, String message) {}
public static class Result {
public boolean valid;
public final List<Issue> issues = new ArrayList<>();
public String error; // null when the verdict is real (TS: error: null)
}
// ---- JSON parser (recursive descent; throws IllegalArgumentException) ----
private final String src;
private int pos;
private JsonSchemaValidator(String src) { this.src = src; }
private void ws() { while (pos < src.length() && " \t\n\r".indexOf(src.charAt(pos)) >= 0) pos++; }
private char peek() { ws(); return pos < src.length() ? src.charAt(pos) : '\0'; }
private Object parseDocument() {
Object v = parseValue();
ws();
if (pos != src.length()) throw new IllegalArgumentException("Invalid JSON");
return v;
}
private Object parseValue() {
char c = peek();
switch (c) {
case '{': {
pos++;
Map<String, Object> m = new LinkedHashMap<>();
if (peek() == '}') { pos++; return m; }
while (true) {
if (peek() != '"') throw new IllegalArgumentException("Invalid JSON");
String key = parseString();
if (peek() != ':') throw new IllegalArgumentException("Invalid JSON");
pos++;
m.put(key, parseValue());
if (peek() == ',') { pos++; continue; }
if (peek() == '}') { pos++; return m; }
throw new IllegalArgumentException("Invalid JSON");
}
}
case '[': {
pos++;
List<Object> a = new ArrayList<>();
if (peek() == ']') { pos++; return a; }
while (true) {
a.add(parseValue());
if (peek() == ',') { pos++; continue; }
if (peek() == ']') { pos++; return a; }
throw new IllegalArgumentException("Invalid JSON");
}
}
case '"': return parseString();
case 't': expect("true"); return Boolean.TRUE;
case 'f': expect("false"); return Boolean.FALSE;
case 'n': expect("null"); return null;
default: return parseNumber();
}
}
private void expect(String word) {
if (!src.startsWith(word, pos)) throw new IllegalArgumentException("Invalid JSON");
pos += word.length();
}
private String parseString() {
pos++; // opening quote
StringBuilder sb = new StringBuilder();
while (true) {
if (pos >= src.length()) throw new IllegalArgumentException("Invalid JSON");
char c = src.charAt(pos);
if (c == '"') { pos++; return sb.toString(); }
if (c == '\\') {
pos++;
char e = src.charAt(pos++);
switch (e) {
case '"': sb.append('"'); break;
case '\\': sb.append('\\'); break;
case '/': sb.append('/'); break;
case 'b': sb.append('\b'); break;
case 'f': sb.append('\f'); break;
case 'n': sb.append('\n'); break;
case 'r': sb.append('\r'); break;
case 't': sb.append('\t'); break;
case 'u': sb.append((char) Integer.parseInt(src.substring(pos, pos + 4), 16)); pos += 4; break;
default: throw new IllegalArgumentException("Invalid JSON");
}
} else if (c < 0x20) {
throw new IllegalArgumentException("Invalid JSON");
} else {
sb.append(c);
pos++;
}
}
}
private Double parseNumber() {
int start = pos;
if (pos < src.length() && (src.charAt(pos) == '-' || src.charAt(pos) == '+')) pos++;
if (pos >= src.length() || !Character.isDigit(src.charAt(pos))) throw new IllegalArgumentException("Invalid JSON");
while (pos < src.length() && Character.isDigit(src.charAt(pos))) pos++;
if (pos < src.length() && src.charAt(pos) == '.') {
pos++;
if (pos >= src.length() || !Character.isDigit(src.charAt(pos))) throw new IllegalArgumentException("Invalid JSON");
while (pos < src.length() && Character.isDigit(src.charAt(pos))) pos++;
}
if (pos < src.length() && (src.charAt(pos) == 'e' || src.charAt(pos) == 'E')) {
pos++;
if (pos < src.length() && (src.charAt(pos) == '-' || src.charAt(pos) == '+')) pos++;
if (pos >= src.length() || !Character.isDigit(src.charAt(pos))) throw new IllegalArgumentException("Invalid JSON");
while (pos < src.length() && Character.isDigit(src.charAt(pos))) pos++;
}
return Double.parseDouble(src.substring(start, pos));
}
// ---- JS-flavoured helpers --------------------------------------------------
// Number.isInteger: finite and equal to its floor.
private static boolean isIntegral(double v) { return !Double.isInfinite(v) && !Double.isNaN(v) && v == Math.floor(v); }
private static String kindOf(Object v) {
if (v == null) return "null";
if (v instanceof Boolean) return "boolean";
if (v instanceof Double d) return isIntegral(d) ? "integer" : "number";
if (v instanceof List) return "array";
if (v instanceof Map) return "object";
return "string";
}
private static boolean deepEqual(Object a, Object b) {
if (!kindOf(a).equals(kindOf(b))) return false;
if (a == null) return true;
if (a instanceof Boolean x) return x.equals(b);
if (a instanceof Double x) return x.equals(b);
if (a instanceof String x) return x.equals(b);
if (a instanceof List<?> x) {
List<?> y = (List<?>) b;
if (x.size() != y.size()) return false;
for (int i = 0; i < x.size(); i++) if (!deepEqual(x.get(i), y.get(i))) return false;
return true;
}
Map<?, ?> x = (Map<?, ?>) a, y = (Map<?, ?>) b;
if (x.size() != y.size()) return false;
for (Map.Entry<?, ?> e : x.entrySet())
if (!y.containsKey(e.getKey()) || !deepEqual(e.getValue(), y.get(e.getKey()))) return false;
return true;
}
// JS Number-to-string: plain integers below 1e21, exponential only past the
// JS thresholds (decimal exponent < -6 or >= 21), minimal exponent digits.
static String jsNum(double v) {
if (v == 0) return "0"; // covers -0
boolean neg = v < 0;
double a = neg ? -v : v;
if (isIntegral(a) && a < 1e21)
return (neg ? "-" : "") + new java.math.BigDecimal(String.valueOf(a)).toBigInteger();
String s = Double.toString(a); // shortest round-trip digits, Java flavour
String mant = s;
int eexp = 0;
int e = s.indexOf('E');
if (e >= 0) { eexp = Integer.parseInt(s.substring(e + 1)); mant = s.substring(0, e); }
int dot = mant.indexOf('.');
String intpart = dot >= 0 ? mant.substring(0, dot) : mant;
String digits = intpart + (dot >= 0 ? mant.substring(dot + 1) : "");
long exp = (long) intpart.length() - 1 + eexp;
int dstart = 0;
while (dstart < digits.length() - 1 && digits.charAt(dstart) == '0') { dstart++; exp--; }
String d = digits.substring(dstart);
StringBuilder sb = new StringBuilder(neg ? "-" : "");
if (exp < -6 || exp >= 21) {
sb.append(d.charAt(0));
if (d.length() > 1) sb.append('.').append(d.substring(1));
sb.append('e').append(exp >= 0 ? "+" : "").append(exp);
} else if (exp < 0) {
sb.append("0.");
for (long i = 0; i < -exp - 1; i++) sb.append('0');
sb.append(d);
} else if (d.length() > exp + 1) {
sb.append(d, 0, (int) (exp + 1)).append('.').append(d.substring((int) (exp + 1)));
} else {
sb.append(d);
for (long i = 0; i < exp + 1 - d.length(); i++) sb.append('0');
}
return sb.toString();
}
// TS .length: UTF-16 code units — astral chars count as 2.
private static int utf16Len(String s) {
int n = 0;
for (int i = 0; i < s.length(); ) {
int cp = s.codePointAt(i);
n += cp > 0xFFFF ? 2 : 1;
i += Character.charCount(cp);
}
return n;
}
// JS String(v) for schema type entries and required keys.
private static String jsStr(Object v) {
if (v == null) return "null";
if (v instanceof Boolean b) return b ? "true" : "false";
if (v instanceof Double d) return jsNum(d);
if (v instanceof String s) return s;
if (v instanceof List<?> l) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < l.size(); i++) { if (i > 0) sb.append(','); sb.append(jsStr(l.get(i))); }
return sb.toString();
}
return "[object Object]";
}
// ---- validator ---------------------------------------------------------------
private static void validate(Object v, Object schema, String path, Result r) {
if (schema instanceof Boolean b) {
if (!b) r.issues.add(new Issue(path, "no value is allowed here (schema is false)"));
return;
}
if (!(schema instanceof Map<?, ?> s)) {
r.issues.add(new Issue(path, "invalid schema node: expected an object or boolean"));
return;
}
Object type = s.get("type");
if (type != null) {
List<?> entries = type instanceof List<?> l ? l : List.of(type);
List<String> allowed = new ArrayList<>();
StringBuilder joined = new StringBuilder();
for (Object e : entries) {
String t = jsStr(e);
allowed.add(t);
if (joined.length() > 0) joined.append('|');
joined.append(t);
}
String actual = kindOf(v);
boolean ok = false;
for (String t : allowed) if (t.equals(actual) || (t.equals("number") && actual.equals("integer"))) ok = true;
if (!ok) r.issues.add(new Issue(path, "expected type " + joined + ", got " + actual));
}
Object en = s.get("enum");
if (en != null) {
List<?> list = en instanceof List<?> l ? l : List.of();
boolean found = false;
for (Object e : list) if (deepEqual(v, e)) { found = true; break; }
if (!found) r.issues.add(new Issue(path, "value not in enum (" + list.size() + " allowed)"));
}
Object konst = s.get("const");
if (konst != null && !deepEqual(v, konst)) r.issues.add(new Issue(path, "value does not match const"));
if (v instanceof Double dv) {
if (s.get("minimum") instanceof Double mn && dv < mn)
r.issues.add(new Issue(path, jsNum(dv) + " is less than minimum " + jsNum(mn)));
if (s.get("maximum") instanceof Double mx && dv > mx)
r.issues.add(new Issue(path, jsNum(dv) + " is greater than maximum " + jsNum(mx)));
if (s.get("exclusiveMinimum") instanceof Double emn && dv <= emn)
r.issues.add(new Issue(path, jsNum(dv) + " is not greater than exclusiveMinimum " + jsNum(emn)));
if (s.get("exclusiveMaximum") instanceof Double emx && dv >= emx)
r.issues.add(new Issue(path, jsNum(dv) + " is not less than exclusiveMaximum " + jsNum(emx)));
}
if (v instanceof String sv) {
int len = utf16Len(sv);
boundCheck(s, "minLength", len, "string length %d is less than minLength %s", path, r);
boundCheck(s, "maxLength", len, "string length %d is greater than maxLength %s", path, r);
Object pat = s.get("pattern");
if (pat instanceof String p) {
try {
if (!java.util.regex.Pattern.compile(p).matcher(sv).find())
r.issues.add(new Issue(path, "string does not match pattern " + p));
} catch (java.util.regex.PatternSyntaxException e) {
r.issues.add(new Issue(path, "invalid pattern in schema: " + p));
}
}
}
if (v instanceof List<?> av) {
boundCheck(s, "minItems", av.size(), "array length %d is less than minItems %s", path, r);
boundCheck(s, "maxItems", av.size(), "array length %d is greater than maxItems %s", path, r);
if (Boolean.TRUE.equals(s.get("uniqueItems")))
for (int i = 0; i < av.size(); i++)
for (int j = i + 1; j < av.size(); j++)
if (deepEqual(av.get(i), av.get(j)))
r.issues.add(new Issue(path + "[" + j + "]", "duplicate item (same as index " + i + ")"));
Object items = s.get("items");
if (items != null)
for (int i = 0; i < av.size(); i++) validate(av.get(i), items, path + "[" + i + "]", r);
}
if (v instanceof Map<?, ?> ov) {
Object req = s.get("required");
if (req instanceof List<?> rl)
for (Object rk : rl) {
String key = jsStr(rk);
if (!ov.containsKey(key)) r.issues.add(new Issue(path, "missing required property \"" + key + "\""));
}
Object props = s.get("properties");
if (props instanceof Map<?, ?> pm)
for (Map.Entry<?, ?> e : pm.entrySet()) {
String key = String.valueOf(e.getKey());
if (ov.containsKey(key)) validate(ov.get(key), e.getValue(), path + "." + key, r);
}
if (Boolean.FALSE.equals(s.get("additionalProperties")))
for (Object key : ov.keySet())
if (!(props instanceof Map<?, ?> && ((Map<?, ?>) props).containsKey(key)))
r.issues.add(new Issue(path + "." + key, "additional property not allowed"));
}
}
private static void boundCheck(Map<?, ?> s, String key, long n, String fmt, String path, Result r) {
Object m = s.get(key);
if (!(m instanceof Double)) return;
double mv = (Double) m;
boolean violated = fmt.contains("less than") ? n < mv : n > mv;
if (violated) r.issues.add(new Issue(path, fmt.replace("%d", String.valueOf(n)).replace("%s", jsNum(mv))));
}
private static boolean blank(String x) { return x.trim().isEmpty(); }
/** Validate a JSON document against a schema. */
public static Result validateJsonSchema(String schemaRaw, String instanceRaw) {
Result r = new Result();
if (blank(schemaRaw) || blank(instanceRaw)) {
r.error = "Both a schema and an instance are required";
return r;
}
Object schema;
try {
schema = new JsonSchemaValidator(schemaRaw).parseDocument();
} catch (RuntimeException e) {
r.error = "Schema: Invalid JSON";
return r;
}
Object instance;
try {
instance = new JsonSchemaValidator(instanceRaw).parseDocument();
} catch (RuntimeException e) {
r.error = "Instance: Invalid JSON";
return r;
}
validate(instance, schema, "$", r);
r.valid = r.issues.isEmpty();
return r;
}
// Example:
// validateJsonSchema(
// "{\"type\":\"object\",\"required\":[\"port\"],\"properties\":{\"port\":{\"type\":\"integer\",\"minimum\":1024}}}",
// "{\"port\":80}").issues.get(0).message()
// → "80 is less than minimum 1024"
public static void main(String[] args) {
Result r = validateJsonSchema(
"{\"type\":\"object\",\"required\":[\"port\"],\"properties\":{\"port\":{\"type\":\"integer\",\"minimum\":1024}}}",
"{\"port\":80}");
System.out.println("valid=" + r.valid + " issues=" + r.issues.size() + " error=" + (r.error == null ? "null" : r.error));
for (Issue i : r.issues) System.out.println(" " + i.path() + ": " + i.message());
}
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →