Disclosure. JSON2Class is our own project. This guide uses its schema utility as an input to a separate Ajv validation exercise. The sensor records and contract rules are synthetic teaching fixtures; they do not describe a real deployed API.
The reader task here is concrete: build a validator that accepts the intended request shapes and rejects the wrong ones. Producing Java DTOs or inspecting inferred types does not answer that question. A validation function needs explicit acceptance rules, representative inputs and observable pass/fail results.
We start with a generated schema draft, make a small set of deliberate contract decisions, and run nine validation cases with Ajv. The point is to turn a convenient starting document into an executable boundary whose behavior can be checked. This is not a claim that generating a schema discovers all the domain rules automatically.
Define what this example should accept
Our fictional sensor interface requires a sensor identifier, a numeric reading, the unit C and a measurements array. A note may be omitted, null or a string. Each measurement must contain a numeric value and may include a string quality label. Unexpected members are rejected at both the root and the measurement-item level.
Those are decisions for this exercise, not facts inferred from one observed record. In an actual application, agree them with the interface owner before placing a validator on an input path. In particular, closing an object to unknown fields is a compatibility choice, not a universal best practice.
This fixture is supposed to be accepted:
{
"sensorId": "sensor-demo",
"reading": 21,
"unit": "C",
"note": null,
"measurements": [
{
"value": 21
},
{
"value": 21.5,
"quality": "estimated"
}
]
}
It deliberately includes a decimal measurement and an optional quality label in the second array element. It also includes a null note. These cases make the fixture useful for testing the contract's boundaries instead of merely validating a document where every field looks identical.
Generate the starting draft and test it before editing
Paste the sample into JSON2Class's JSON Schema Generator. The deployed helper captured in our lab generates a starting draft with observed members required, closed object shapes, and array-item inference based on the first element.
The lab compiled that unedited draft with Ajv and validated the original sample. The result was false. Its inferred item value type is integer and its item object excludes quality, so the second measurement does not fit the proposed rule. This is an actual recorded validation result, not a hypothetical warning about what a validator might do.
Keep this failing fixture when reviewing a generated contract. It reveals a mismatch immediately and gives your later edits a reason. Do not quietly simplify the sample by deleting the decimal measurement just to make the draft pass; that would hide a legitimate case the agreed interface is supposed to accept.
The generator still saves typing for the starting shape. The useful transition is to a maintained schema with explicit acceptance tests, rather than treating the first inferred document as the final authority.
Make the reviewed contract explicit
The lab changes the generated draft to allow numeric readings, make note optional and nullable, describe measurement items explicitly, and restrict the demonstration's unit to C. It also declares the schema dialect used by the exercise.
Here is the resulting maintained schema, captured from the runner:
{
"type": "object",
"properties": {
"sensorId": {
"type": "string"
},
"reading": {
"type": "number"
},
"unit": {
"type": "string",
"enum": [
"C"
]
},
"note": {
"type": [
"string",
"null"
]
},
"measurements": {
"type": "array",
"items": {
"type": "object",
"properties": {
"value": {
"type": "number"
},
"quality": {
"type": "string"
}
},
"required": [
"value"
],
"additionalProperties": false
}
}
},
"required": [
"sensorId",
"reading",
"unit",
"measurements"
],
"additionalProperties": false,
"$schema": "http://json-schema.org/draft-07/schema#"
}
Notice that the root required list does not contain note. Its property type still matters when the member is present. A string note and a null note are allowed, but an object-valued note would not be allowed by that rule. Presence and value type are separate decisions.
The measurements array has an explicit object item schema. Value is required and numeric; quality is optional and textual. Both the root and the item object remain closed to extra members. Changing the root rule alone would not change the item rule, so review each object boundary deliberately.
The JSON Schema object reference defines the relevant keywords. It does not tell you whether your particular provider promises an optional note or forward-compatible extra fields. That decision must come from the contract you are maintaining.
Compile a validator and observe its boolean result
The exercise ran with Ajv 8.20.0 and Node.js 22.22.2. Save the sample shown above as sample.json and the reviewed schema as schema.json. Place the following standalone script in validate-demo.mjs beside those files. It compiles a validation function and checks the sample:
import Ajv from "ajv";
import fs from "node:fs/promises";
const schema = JSON.parse(await fs.readFile(
new URL("./schema.json", import.meta.url), "utf8"
));
const payload = JSON.parse(await fs.readFile(
new URL("./sample.json", import.meta.url), "utf8"
));
const ajv = new Ajv({ strict: true, allErrors: true });
const validate = ajv.compile(schema);
console.log(validate(payload));
The recorded console result is true. The demo file is included in the lab and was executed, so the displayed code is not reconstructed from a screenshot. You can also reproduce it in a new local folder using the two JSON blocks above, without access to the blog repository. Install Ajv 8.20.0 in that folder and run node validate-demo.mjs.
Consult Ajv's getting-started guide for the compiler and validation API. Our runner copies each errors array before validating the next fixture so the report preserves the result associated with that particular input. It does not infer successful application behavior merely because compilation completed.
Keep accepting and rejecting fixtures together
The runner validated these cases against the reviewed schema:
| Validation fixture | Observed result |
|---|---|
| original sample | PASS |
| missing optional note | PASS |
| string note | PASS |
| fractional reading | PASS |
| missing sensor identifier | REJECT |
| string reading | REJECT |
| unknown root field | REJECT |
| unknown item field | REJECT |
| wrong unit | REJECT |
The first four checks establish intended acceptance behavior: the original sample, an omitted note, a textual note and a fractional reading all pass. These cases ensure that a supposedly optional field has not accidentally remained mandatory and that valid numbers are not restricted to integers.
The other checks establish rejection behavior. An absent sensor identifier fails the required rule. A string reading fails the type rule. Unexpected root and item members fail their respective closed-object rules. The wrong unit fails the explicit enumeration used by this demonstration.
A collection of only passing fixtures would not show that the validator enforces the boundary. A collection of only failing fixtures would not show that legitimate clients can use it. Keep both sets and review a changed expectation as a contract change, rather than automatically updating the fixture to match whatever the implementation currently does.
Integrate validation without silently reshaping requests
The lab validates already-parsed objects. It does not make an HTTP request or install a server middleware. In a real integration, parse the document through the application's supported path, validate it against the maintained contract, and make the acceptance or rejection observable to the caller and operator.
The demonstrated setup does not enable type coercion, removal of unknown properties or insertion of defaults. A textual number therefore remains textual and fails the relevant type check. If your application chooses transformations, document them and test their effects separately from the validation decision. A caller should not have to guess whether invalid input was rejected or silently rewritten.
Avoid compiling the same schema inside every request handler. Keep the schema and its compiled validator in the application's intended lifecycle, then rerun the fixtures when either the contract or validator dependency changes. This exercise does not supply throughput measurements or promise the same operational characteristics in every runtime.
Distinguish request contracts from response compatibility
Our closed demonstration shape is an explicit input policy. It should not automatically become a consumer's policy for a third-party response that may gain additional members. Reuse the approach to acceptance tests, not every rule from this example.
When deciding to tolerate extra fields, adjust the relevant object boundary and add a fixture demonstrating the new policy. When changing optionality or a numeric restriction, update both accepting and rejecting cases. Explain what clients should expect during a migration instead of treating the edit as a formatting cleanup.
The JSON Diff response-review guide helps inspect changed samples, but a readable diff is not an executable validation contract. The JSONPath extraction guide helps isolate a nested subtree, but selection alone does not establish that the surrounding request is valid.
Run the evidence and use the tools deliberately
From the blog repository, install its locked dependencies and run the exercise:
npm ci
node examples/json2class-seo-lab/run.mjs
node examples/json2class-seo-lab/validate-demo.mjs
The runner checks the unedited draft's rejection, the reviewed schema's nine cases and the other tool examples. It records results in results.json, with the schema helper's provenance identified in the snapshot manifest. The checks are a small reproducible validation lesson, not a complete JSON Schema conformance or browser-privacy audit.
Use the JSON Schema Generator to prepare a starting shape, then maintain the actual contract and its acceptance tests in your application. Browse the JSON2Class developer tools for related payload utilities. If you need to apply an explicit configuration edit after validating its shape, the JSON Patch review guide covers that separate operation.
