Generate a JSON Schema from a Java class by serializing a representative instance to strict JSON, inferring its Draft 2020-12 structure, and validating the result.

The important boundary is that JSON Schema describes serialized JSON, not Java fields directly. The JSON Schema Generator does not read Java source, inspect annotations, or execute a class; it converts one strict JSON value into a reviewable structural schema.

For a Java project, create representative instances, serialize them with the same JSON library and configuration used by the API, then complete the inferred schema from authoritative requirements.

how to generate json schema from java class
How to Generate JSON Schema from a Java Class

Choose the right generation strategy

A Java class, a serialized sample, and an API contract provide different kinds of evidence. Treating them as interchangeable can produce a schema that validates one example but does not represent the actual service contract.

Source Use it to establish Do not infer from it alone
Java object, class, and serializer configuration The actual JSON property names, nesting, value shapes, null handling, and enum or date representation Requirements for unseen request variants, business constraints, or whether unknown properties are forbidden
Representative strict JSON Observed object structure, property presence, nullability, array item types, and mixed value types Formats, enums, numeric bounds, string patterns, or fields that never appeared in the sample
Authoritative API requirements Required properties, permitted values, ranges, formats, defaults, and closed-object policy A ready-to-use schema without translating and testing those requirements
Generated Draft 2020-12 schema A candidate validation structure inferred from the sample Proof that the complete Java model or API contract has been captured

If you require direct generation from class metadata, use a Java-aware generator that supports your chosen annotations and binding rules. The browser-based workflow described here begins after the class has produced JSON.

Generate the schema from a Java class

  1. Identify the root Java type and the exact JSON view clients receive. Record the serializer's property-naming, null and default inclusion, enum, date, and nested-type settings so the schema does not describe a representation the API never emits.
  2. Create representative instances that cover every contract-valid shape you need to observe, including nested objects, populated arrays, explicit nulls, and mixed types only where the API permits them. When you supply an array of object samples, the generator can merge property presence across those objects; a single object cannot reveal a field that is absent.
  3. Serialize the instance to strict JSON with the same library and configuration used at the API boundary. Preserve null as null when the API does, and confirm the emitted property names instead of assuming they match the Java field names.
  4. Paste the strict JSON into the JSON Schema Generator, enter a concise schema title if useful, and generate the schema. Parsing and inference remain in the current tab, and the sample is not uploaded.
  5. Inspect required fields, nullability, array item types, anyOf branches, and object openness. A property present in every merged object sample is required, while a property missing from at least one sample is not required. Arrays infer items from every observed element, compatible mixed numbers widen from integer to number, and incompatible types become anyOf branches. Explicit null adds null to a directly typed schema; more complex combinations use anyOf.
  6. Add formats, enums, ranges, requiredness corrections, and closed-object policy from authoritative requirements only. The generator deliberately avoids guessing semantics that a sample cannot establish.
  7. Copy the schema and test both accepted and rejected instances with a validator that explicitly supports Draft 2020-12, using the same configuration and vocabulary as production.

Example representative shape: {"id":"A-17","name":"Widget","price":19.5,"active":true,"tags":["blue"],"notes":null}

This example establishes structural types, not business rules. It does not prove that price has a particular range, that id follows a pattern, or that notes may always be null.

Match the inferred schema to Java types

Use the generated schema to confirm how the Java model is serialized, not to reconstruct the original class. JSON can reveal a value's structural type, but it usually discards the Java-specific distinction behind that value.

Observed JSON Check against the Java side Generator behavior
string String, enum, identifier, or date-like value Produces string only; it does not add a format or enum
safe integer An integral field, although its exact Java width cannot be recovered Produces integer
other number Floating-point or decimal field Produces number
boolean Primitive or wrapper boolean Produces boolean
null A nullable Java representation Adds null to a directly typed schema while retaining its properties or items
array Array or collection element type Uses every observed element for items; an empty array emits an empty items schema
object POJO, record, or map shape Produces properties and required, but leaves additionalProperties unspecified

The tool cannot determine whether a string is an enum, UUID, date, or arbitrary text, nor whether a number originated from an integer, floating-point field, or decimal type. JavaScript parses the sample number before inference, so only safe integers become integer; larger rounded values are not exact evidence. For precision-sensitive decimals and identifiers, use strings when the API contract permits it and add application validation.

Add only constraints you can justify

Structural inference deliberately stops before business semantics. Add the following only when they come from documented requirements:

  • Required and optional properties across all real request variants
  • String formats and patterns, plus allowed enum or const values
  • Numeric minimum, maximum, and multipleOf rules
  • Length and uniqueness constraints
  • Descriptions, defaults, examples, deprecation, readOnly or writeOnly status, and content encoding
  • References, anchors, IDs, conditional logic, unevaluated properties, and other business rules

Generated objects remain open because one sample cannot prove that unseen keys are forbidden. The schema therefore omits additionalProperties. Add additionalProperties: false only when the authoritative contract explicitly prohibits unknown properties.

Java primitive, boxed, Optional, or Bean Validation semantics do not become schema keywords automatically. Translate only rules documented for your JSON binding and API, then test those rules with the deployed validator.

Respect strict JSON and generator limits

Before submitting a large serialized fixture, check the documented boundaries:

  • 500,000 input characters
  • 50,000 values
  • 40 nesting levels
  • 1,000,000 output characters

A boundary failure emits no partial schema, so reduce or restructure the input rather than treating an incomplete result as usable.

The input must be strict JSON. Comments, trailing commas, NaN, Infinity, undefined, BigInt, and JavaScript-only literals fail instead of being coerced. If the Java serialization boundary produces a non-JSON token, correct that output before attempting inference.

Parsing and inference stay in the current tab. The page does not upload the sample, run a validator, or contact a schema registry, so copying the result into your chosen Draft 2020-12 validator is a separate and necessary step.

Test the schema like production

Use a validator that explicitly supports JSON Schema Draft 2020-12. The copied schema remains a candidate until it demonstrates the expected behavior.

  • Accept a representative valid payload
  • Reject a missing field when the authoritative contract requires it
  • Reject an incorrect primitive type
  • Reject explicit null where null is forbidden
  • Reject an incorrect array item type
  • Accept or reject mixed item types according to the API contract
  • Enforce the unknown-key policy when the object is intentionally closed

Draft 2020-12 does not guarantee that every validator asserts format; an implementation may treat it as annotation-only unless assertion behavior is enabled. Test with the exact validator, configuration, and vocabulary used in production instead of assuming every library interprets every keyword identically.

Make the conversion repeatable

For a team workflow, commit the representative JSON fixture and the reviewed schema. Regenerating the same input produces stable text suitable for review and version control, so schema diffs can highlight changed samples or manual requirement updates.

Regenerate and revalidate the schema whenever serialization behavior or API requirements change. Keep Java-aware class generation or a hand-authored schema alongside the sample-derived schema when annotations are the source of truth, and reconcile any differences instead of treating structural inference as proof.

The practical Java workflow is therefore: create the model, serialize a valid representative value, infer a structural Draft 2020-12 schema, add authoritative constraints, and verify the result in the production validation environment.

If you're weighing options, JSON to CSV: Command Line vs Online Compared covers this in detail.

If you're weighing options, JSON to Excel API Alternative: Local XLSX Workflow covers this in detail.