JSON Schema classes

When the application lists JSON Schemas in spring.json.schemas, the build writes a Dart class for each object in them. The classes are @Introspected, so the ObjectMapper reads and writes them without a hand-written fromJson, and the JSON is checked against the schema when it is read.

Why

A partner publishes a JSON Schema for its orders. Writing the classes by hand means copying every property, and the copy drifts when the schema changes. Here the schema is the source: change its version or its file and the classes follow at the next build. Remote schemas are kept as resources of the app, so the running app needs no network.

Example

# lib/resources/application.yml
spring:
  json:
    schemas:
      - location: resources:schemas/order.json
      - location: https://example.com/schemas/user.json
        sha256: 3f1c...          # the download is refused with another
      - location: github:acme/contracts/schemas/invoice.json@v2
        prefix: Api              # ApiInvoice, ApiInvoiceLine
        name: Invoice            # the root class, instead of its title

Run the build (dart run build_runner build). Then use the classes:

@Service()
class Orders {
  Orders(this.mapper);
  final ObjectMapper mapper;

  Order parse(String json) => mapper.readValue<Order>(json);
}

Invalid JSON throws a JsonSchemaValidationException that lists every violation (see JSON Schema).

The keys

Key Meaning
spring.json.schemas[n].location Where the schema is: resources:path (a file below lib/resources/), https://..., http://... or github:owner/repo/path/to/file.json@ref (@ref is optional)
spring.json.schemas[n].sha256 The SHA-256 (hex) of a remote schema. The build refuses a download with another digest
spring.json.schemas[n].prefix What the names of the classes of this schema start with: Api makes ApiInvoice and ApiInvoiceLine
spring.json.schemas[n].name The name of the root class, instead of the schema's title

The build reads the keys as the application reads them without a profile (see Properties the build reads). Put them in application.yml or application.properties.

What a schema becomes

In the schema In Dart
An object with properties A class; each property is a final field
A property in required and not nullable A required named parameter
Any other property A nullable field
$defs and inline objects Classes of their own (OrderLine, or the parent's name and the property's)
string String
string with format: date-time DateTime
integer int
number double
boolean bool
array List
An object with additionalProperties only Map<String, ...>
A string enum A Dart enum whose values keep their JSON text
type: [x, "null"], or anyOf / oneOf of one type and null The type, nullable
allOf of objects One class with their properties together
Any other anyOf / oneOf, a type list of several kinds, a $ref to a schema not in spring.json.schemas Object?, with a warning that names the place
minLength / maxLength, minItems / maxItems @Size
minimum / maximum @Min / @Max (@DecimalMin / @DecimalMax for numbers)
pattern @Matches
format: email @Email
description The doc comment of the field or class

A $ref to another schema listed in spring.json.schemas uses that schema's class.

A generated class

For this schema:

{
  "title": "User",
  "type": "object",
  "required": ["email"],
  "properties": {
    "email": {"type": "string", "format": "email", "description": "The login."},
    "age": {"type": "integer", "minimum": 18},
    "role": {"enum": ["admin", "guest"]}
  }
}

the build writes classes of this shape:

// lib/spring_gen/json_schemas.spring.classes.dart (part of main.spring.dart)
enum UserRole {
  /// `admin`.
  admin,

  /// `guest`.
  guest,
}

Object? _$UserRoleJson(UserRole value) => switch (value) {
  UserRole.admin => r'admin',
  UserRole.guest => r'guest',
};

@_sj.JsonSchemaSource(r'https://example.com/schemas/user.json')
@_sj.JsonInclude(_sj.JsonInclusion.nonNull)
class User {
  /// The User of these values.
  const User({required this.email, this.age, this.role});

  /// The login.
  @_sj.Email()
  final String email;

  /// JSON `age`.
  @_sj.Min(18)
  final int? age;

  /// JSON `role`.
  final UserRole? role;

  @override
  String toString() => 'User(email: $email, age: $age, role: $role)';
}

The classes are a part of the app's .spring.dart, which imports the core as _sj; their introspection is in the app's module, not on the class, so no @Introspected is written. The root class carries @JsonSchemaSource with the location, so the mapper checks JSON against that schema. Every class has @JsonInclude(nonNull), so an absent property is not written as null, which the schema might refuse. An enum keeps each value's JSON text (_$UserRoleJson).

Where it goes

The classes are in lib/spring_gen/json_schemas.spring.classes.dart, a part of the application's .spring.dart library (the one of @SpringBootApplication, else the outermost @ComponentScan), the way the typed keys are. The module of the build gets their introspections. Without such a library, the build warns and writes no file.

A remote schema is also embedded as a resource of the app, at json-schemas/<host or github>/<path>.json (JsonSchemaLocations.resourceOf). The jsonSchemaRegistry bean reads it from there, so the running app never goes to the network (see JSON Schema beans).

Downloads

Pin a schema you do not own with sha256: it is the only guard against the server changing it under you.

Name clashes

The classes share one namespace in the application's library. A class with the name of a class of Spring for Dart (Order, for one) gets a warning at build time: an application that imports both must hide one. Change the name with prefix: (Api gives ApiOrder), or hide one in the import:

import 'package:spring_core_dart/spring_core_dart.dart' hide Order;

In Spring (Java)

Spring has no counterpart. In Java, jsonschema2pojo does the same as a Maven or Gradle plugin; its classes are Jackson classes. Here the classes are @Introspected, and the check against the schema is built in through @JsonSchemaSource.

See also