
# JSON Schema

`JsonSchema` checks decoded JSON against a JSON Schema (draft 2020-12) and lists every place that does not fit, with its JSON pointer.

## Why

JSON from outside is not trusted: a request body, a file a user edited, a message from a partner. A `fromJson` stops at the first problem and often with a message about Dart, not about the JSON. A schema is a file that partners can read, and a check against it gives all the problems at once, each with its path. The same schema can also be published, and the build can write the classes of a schema for you (see [JSON Schema classes](../../spring-core-dart-generator/json-schema-classes.md)).

## Example

An order with a pattern for the id, an email, a status from a list, and at least one line:

```dart
import 'dart:convert';

import 'package:spring_core_dart/json.dart';

final schema = JsonSchema.parse(orderSchemaText);

final result = schema.validate(jsonDecode(body));
if (!result.isValid) {
  for (final violation in result.violations) {
    print(violation);
  }
}
```

For a body with several mistakes, it prints:

```text
/id: must match the pattern ^ORD-[0-9]+$
/email: must be a valid email
/status: must be one of: new, paid, shipped
/items/0/qty: must be at least 1
/items/0/color: is not allowed
/items/1/sku: is required
/items/1/price: must be greater than 0
```

The schema is:

```json
{
  "type": "object",
  "required": ["id", "email", "status", "items"],
  "properties": {
    "id": {"type": "string", "pattern": "^ORD-[0-9]+$"},
    "email": {"type": "string", "format": "email"},
    "status": {"enum": ["new", "paid", "shipped"]},
    "items": {
      "type": "array",
      "minItems": 1,
      "items": {"$ref": "#/$defs/OrderLine"}
    }
  },
  "$defs": {
    "OrderLine": {
      "type": "object",
      "required": ["sku", "qty", "price"],
      "additionalProperties": false,
      "properties": {
        "sku": {"type": "string"},
        "qty": {"type": "integer", "minimum": 1},
        "price": {"type": "number", "exclusiveMinimum": 0}
      }
    }
  }
}
```

`JsonSchema.parse` takes the text; `JsonSchema(document)` takes a decoded `Map`. A text that is not JSON, or not a schema, throws a `FormatException`. The schemas `true` (accepts everything) and `false` (accepts nothing) are valid schemas too.

## Violations

`validate` takes decoded JSON (what `jsonDecode` returns) and gives a `JsonSchemaResult`:

| Member | Meaning |
|---|---|
| `isValid` | `true` when there is no violation |
| `violations` | A list of `JsonSchemaViolation`, in document order |

| `JsonSchemaViolation` | Meaning |
|---|---|
| `path` | The JSON pointer of the value: `/items/1/sku`. Empty for the whole document |
| `keyword` | The keyword that failed: `required`, `minimum`, `pattern`... |
| `message` | What is wrong: `must be at least 1` |

`toString()` gives `path: message`, with `(root)` for the whole document.

## Several documents and $ref

A `$ref` to a place in the same document (`#/$defs/OrderLine`, `#anchor`) needs nothing more. A `$ref` to another document is looked up in a `JsonSchemaRegistry` by its absolute URI. A `$ref` is resolved against the base URI, which comes from the `$id`s around it.

```dart
final registry = JsonSchemaRegistry()
  ..add(JsonSchema.parse(addressJson)); // its $id: https://x.org/address.json

final order = JsonSchema.parse(
  '{"\$id": "https://x.org/order.json",'
  ' "properties": {"to": {"\$ref": "address.json"}}}',
  registry: registry,
);
```

| `JsonSchemaRegistry` | Does |
|---|---|
| `JsonSchemaRegistry([schemas])` | A registry with these schemas |
| `add(schema, {uri})` | Adds a schema under `uri`, else under its `$id`. Neither: an `ArgumentError`. A later schema for the same URI replaces the earlier one |
| `resolve(uri)` | The schema known by `uri` (the fragment is ignored), also a subschema with that `$id`; `null` when there is none |
| `schemas` | The schemas added, by URI (read only) |

A `$ref` that loops without reaching a value is reported as a violation, not followed forever. In an application the registry is a bean: see [JSON Schema beans](../../spring-boot-dart/json-schema.md).

## The schema of a class

`JsonSchemaGenerator` writes the schema of an `@Introspected` class from its introspection, without reflection. The schema describes the JSON the `ObjectMapper` writes and reads: JSON names (`@JsonProperty`, `@JsonNaming`), left-out properties (`@JsonIgnore`), `readOnly` and `writeOnly`, and the validation constraints as keywords.

```dart
final generator = JsonSchemaGenerator();

generator.schemaOf(Order);      // one class, its classes in $defs
generator.schemasOf([Order]);   // by class name
generator.all();                // every introspected class, by name
```

`schemaOf` throws an `ArgumentError` for a class that is not introspected. `all()` leaves out enums and generic classes, and of two classes with the same name keeps the first. Pass `namingStrategy:` when your mapper uses another naming strategy than `lowerCamelCase`.

| Dart | Schema |
|---|---|
| `String`, `int`, `double` and `num`, `bool` | `string`, `integer`, `number`, `boolean` |
| `DateTime` | `string`, format `date-time` |
| `Duration` | `string`, format `duration` |
| `Uri` | `string`, format `uri-reference` |
| `BigInt` | a string of digits or an integer |
| an enum | `enum` with its JSON values (`@JsonValue` too) |
| `List`, `Set` | `array` with `items`; `Set` adds `uniqueItems` |
| `Map` | `object` with `additionalProperties` |
| an introspected class | a `$ref` to `#/$defs/<ClassName>`; the root class is `#`, so cycles work |
| a nullable type | the type or `null` |
| `dynamic`, `Object`, `JsonNode` | anything |

`required` lists the constructor parameters the mapper needs (required, not nullable, not read-only) and the properties marked `@NotNull`. These constraints become keywords: `@NotEmpty`, `@NotBlank`, `@Size`, `@Min`, `@Max`, `@DecimalMin`, `@DecimalMax`, `@Positive`, `@PositiveOrZero`, `@Negative`, `@NegativeOrZero`, `@Matches` (anchored, without its flags), `@Email` and `@Each` (for the elements).

Not described: polymorphism (`@JsonTypeInfo`), `@JsonUnwrapped` properties, classes with their own `fromJson` / `toJson` (any JSON), and the mapper settings that write dates and durations as numbers. The [actuator's `jsonschemas` endpoint](../../spring-boot-actuator/json-schemas.md) shows these schemas of a running application.

## Checking while reading: @JsonSchemaSource

Put `@JsonSchemaSource` on a class whose JSON comes from outside and has a published schema:

```dart
@Introspected()
@JsonSchemaSource('resources:schemas/order.json')
class Order {
  const Order({required this.id, required this.items});
  final String id;
  final List<OrderItem> items;
}
```

When the `ObjectMapper` has a `schemaResolver`, it checks the decoded JSON of such a class against the schema before it builds the object. A mistake throws a `JsonSchemaValidationException` that lists every violation:

```dart
final mapper = ObjectMapper(
  schemaResolver: (location) => schemas[location],
);

try {
  mapper.readValue<Order>(json);
} on JsonSchemaValidationException catch (error) {
  for (final violation in error.violations) {
    print('${violation.path}: ${violation.message}');
  }
}
```

- The `location` is `resources:schemas/order.json` (a file below `lib/resources/`), `https://example.com/schemas/order.json` (or `http://`) or `github:owner/repo/path/to/order.json@ref` (`@ref` is optional).
- The resolver gets the location and gives a `JsonSchema`, or `null`: then nothing is checked. It is asked once per location.
- The check also runs when the class is a property, a list element or a map value of the class being read. A class read by a `JsonDeserializer` is not checked.
- `JsonSchemaValidationException` is a `JsonMappingException`. `violations` are inside the checked value, `path` says where that value is in the document, and `location` names the schema. The web starter turns it into a 400 response, as for any other `JsonMappingException`.
- A remote schema is downloaded at build time and kept below `lib/resources/`, so it is read like a resource. `JsonSchemaLocations.resourceOf(location)` gives its path (`json-schemas/example.com/schemas/order.json`) and `JsonSchemaLocations.isRemote(location)` tells a download from a `resources:` file.

In an application you do not write the resolver: the `ObjectMapper` bean gets the registry, which holds the schemas named by `@JsonSchemaSource` and `spring.json.schemas` (see [JSON Schema beans](../../spring-boot-dart/json-schema.md)). The build can also write the classes for a schema, with `@JsonSchemaSource` on the root one (see [JSON Schema classes](../../spring-core-dart-generator/json-schema-classes.md)).

## Supported keywords

| Group | Keywords |
|---|---|
| Types and values | `type` (also a list, and `integer`), `enum`, `const` |
| Objects | `properties`, `required`, `additionalProperties`, `patternProperties`, `propertyNames`, `minProperties`, `maxProperties`, `dependentRequired`, `dependentSchemas` |
| Arrays | `items`, `prefixItems`, `minItems`, `maxItems`, `uniqueItems`, `contains`, `minContains`, `maxContains` |
| Strings | `minLength`, `maxLength` (in Unicode code points), `pattern`, `format` |
| Numbers | `minimum`, `maximum`, `exclusiveMinimum`, `exclusiveMaximum`, `multipleOf` |
| Combining | `allOf`, `anyOf`, `oneOf`, `not`, `if` / `then` / `else` |
| Documents | `$ref`, `$defs` (and `definitions`), `$id`, `$anchor`, the schemas `true` and `false` |

`pattern` is a Dart `RegExp` in Unicode mode and is not anchored. Other keywords (`title`, `description`, `default`, `examples`...) are ignored.

### Formats

| Format | Valid when |
|---|---|
| `date-time` | RFC 3339: `2026-01-31T12:00:00.5+02:00` (a `T`, and an offset or `Z`) |
| `date` | `2026-01-31`, a real calendar day |
| `time` | `12:00:00Z`, with its offset |
| `email` | a local part, `@` and a domain, no spaces (not every rule of RFC 5321) |
| `uri` | a URI with a scheme |
| `uri-reference` | any URI, also a relative one |
| `uuid` | 8-4-4-4-12 hexadecimal digits |
| `ipv4` | four numbers from 0 to 255 without leading zeros |
| `ipv6` | what `Uri.parseIPv6Address` accepts |

Other formats are ignored, and so is `format` on a value that is not a string. `JsonSchemaFormats.isValid(format, value)` runs the same check by hand.

## Limits

- `unevaluatedProperties`, `unevaluatedItems` and `$dynamicRef` are not supported: they are ignored.
- The `duration` format is not checked, though the generator writes it for a `Duration`.
- Other formats than the ones above are not checked.

## In Spring (Java)

Spring has no JSON Schema support. Java applications use a library: networknt's `json-schema-validator` to check JSON, and Jackson's `jsonSchema` module or victools' `jsonschema-generator` to write a schema from a class. `JsonSchema` and `JsonSchemaGenerator` play those roles here, and `@JsonSchemaSource` with `schemaResolver` has no counterpart.

## See also

- [JSON](index.md)
- [JSON Schema beans](../../spring-boot-dart/json-schema.md)
- [JSON Schema classes](../../spring-core-dart-generator/json-schema-classes.md)
- [The jsonschemas endpoint](../../spring-boot-actuator/json-schemas.md)
