JSON Schema のクラス

アプリケーションが spring.json.schemas に JSON Schema を列挙すると、ビルドはその中の各オブジェクトに Dart のクラスを書き出します。クラスは @Introspected なので、ObjectMapper は手書きの fromJson なしで読み書きでき、JSON は読むときにスキーマに照らして検査されます。

使う理由

取引先が注文の JSON Schema を公開しているとします。クラスを手で書くとすべてのプロパティを写すことになり、スキーマが変わるとそのコピーはずれていきます。ここではスキーマが元です。バージョンやファイルを変えれば、次のビルドでクラスもそれに従います。リモートのスキーマはアプリケーションのリソースとして保存されるので、動作中のアプリケーションにネットワークは要りません。

例

# lib/resources/application.yml
spring:
  json:
    schemas:
      - location: resources:schemas/order.json
      - location: https://example.com/schemas/user.json
        sha256: 3f1c...          # 別のものをダウンロードすると拒否される
      - location: github:acme/contracts/schemas/invoice.json@v2
        prefix: Api              # ApiInvoice、ApiInvoiceLine
        name: Invoice            # title の代わりのルートクラス名

ビルド (dart run build_runner build) を実行し、クラスを使います。

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

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

不正な JSON は、すべての違反を列挙した JsonSchemaValidationException を投げます (JSON Schema を参照)。

キー

キー 意味
spring.json.schemas[n].location スキーマの場所。resources:path (lib/resources/ の下のファイル)、https://...、http://...、github:owner/repo/path/to/file.json@ref (@ref は省略可)
spring.json.schemas[n].sha256 リモートのスキーマの SHA-256 (十六進)。別のダイジェストのダウンロードをビルドは拒否します
spring.json.schemas[n].prefix このスキーマのクラスの名前の先頭に付くもの。Api なら ApiInvoice と ApiInvoiceLine
spring.json.schemas[n].name スキーマの title の代わりのルートクラスの名前

ビルドは、アプリケーションがプロファイルなしで読むのと同じようにキーを読みます (ビルドが読むプロパティ を参照)。キーは application.yml または application.properties に置いてください。

スキーマがなるもの

スキーマ Dart
properties を持つオブジェクト クラス。各プロパティは final フィールド
required にあり、null 非許容のプロパティ 必須の名前付きパラメーター
それ以外のプロパティ null 許容のフィールド
$defs とインラインのオブジェクト それぞれ独立したクラス (OrderLine、または親の名前とプロパティの名前)
string String
format: date-time の string DateTime
integer int
number double
boolean bool
array List
additionalProperties だけのオブジェクト Map<String, ...>
文字列の enum 値が JSON のテキストを保つ Dart の enum
type: [x, "null"]、または一つの型と null の anyOf / oneOf その型の null 許容
オブジェクトの allOf プロパティをまとめた一つのクラス
それ以外の anyOf / oneOf、複数の種類の型リスト、spring.json.schemas にないスキーマへの $ref Object?。場所を示す警告つき
minLength / maxLength、minItems / maxItems @Size
minimum / maximum @Min / @Max (小数は @DecimalMin / @DecimalMax)
pattern @Matches
format: email @Email
description フィールドまたはクラスのドキュメントコメント

spring.json.schemas に列挙された別のスキーマへの $ref は、そのスキーマのクラスを使います。

生成されるクラス

次のスキーマからは、

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

ビルドは次のような形のクラスを書き出します。

// 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)';
}

クラスはアプリの .spring.dart のパートで、そのファイルはコアを _sj として import します。イントロスペクションはクラスではなくアプリのモジュールにあるので、@Introspected は書かれません。ルートのクラスは location つきの @JsonSchemaSource を持つので、マッパーはその JSON をそのスキーマに照らして検査します。すべてのクラスに @JsonInclude(nonNull) が付くので、ないプロパティは、スキーマが拒否するかもしれない null としては書き出されません。列挙型は値ごとに JSON のテキストを保ちます (_$UserRoleJson)。

書き出される場所

クラスは lib/spring_gen/json_schemas.spring.classes.dart に書かれます。これはアプリケーションの .spring.dart ライブラリ (@SpringBootApplication のもの、なければ最も外側の @ComponentScan) の part で、型付きキーと同じ仕組みです。ビルドのモジュールがそれらのイントロスペクションを受け取ります。そのようなライブラリがないと、ビルドは警告し、ファイルを書きません。

リモートのスキーマは、アプリケーションのリソースとしても json-schemas/<ホストまたは github>/<パス>.json に埋め込まれます (JsonSchemaLocations.resourceOf)。jsonSchemaRegistry Bean はそこから読むので、動作中のアプリケーションがネットワークに出ることはありません (JSON Schema の Bean を参照)。

ダウンロード

自分のものではないスキーマは sha256 でピン留めしてください。サーバーが知らないうちにスキーマを変えることに対する唯一の防御です。

名前の衝突

クラスは、アプリケーションのライブラリの一つの名前空間を共有します。Spring for Dart のクラスと同じ名前のクラス (たとえば Order) は、ビルド時に警告されます。両方をインポートするアプリケーションは、どちらかを hide しなければなりません。prefix: で名前を変える (Api なら ApiOrder) か、インポートで一方を hide します。

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

Spring (Java) との対応

Spring に相当するものはありません。Java では jsonschema2pojo が Maven や Gradle のプラグインとして同じことをし、そのクラスは Jackson のクラスです。ここではクラスは @Introspected で、スキーマに照らした検査は @JsonSchemaSource によって組み込まれています。

関連項目