JSON Schema

JsonSchema は、デコードした JSON を JSON Schema (draft 2020-12) に照らして検査し、合わない箇所をすべて JSON ポインターつきで列挙します。

使う理由

外から来る JSON は信用できません。リクエストボディ、ユーザーが編集したファイル、取引先からのメッセージなどです。fromJson は最初の問題で止まり、メッセージも JSON ではなく Dart についてのものになりがちです。スキーマは取引先も読めるファイルで、それに照らした検査はすべての問題を、それぞれのパスつきで一度に返します。同じスキーマを公開することもでき、ビルドがスキーマのクラスを書き出すこともできます (JSON Schema のクラス を参照)。

例

id のパターン、メールアドレス、一覧にあるステータス、少なくとも一行の明細を持つ注文です。

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

間違いがいくつもあるボディでは、次のように出力されます。

/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

スキーマは次のとおりです。

{
  "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 はテキストを、JsonSchema(document) はデコード済みの Map を受け取ります。JSON ではないテキストやスキーマではないテキストは FormatException を投げます。true (すべてを受け入れる) と false (何も受け入れない) もスキーマとして有効です。

違反

validate はデコード済みの JSON (jsonDecode が返すもの) を受け取り、JsonSchemaResult を返します。

メンバー 意味
isValid 違反がなければ true
violations JsonSchemaViolation のリスト。文書の順
JsonSchemaViolation 意味
path 値の JSON ポインター。/items/1/sku。文書全体なら空
keyword 失敗したキーワード。required、minimum、pattern など
message 何が間違っているか。must be at least 1

toString() は path: message を返し、文書全体は (root) になります。

複数の文書と $ref

同じ文書の中への $ref (#/$defs/OrderLine、#anchor) には、追加の設定は要りません。別の文書への $ref は、絶対 URI で JsonSchemaRegistry から探します。$ref はベース URI を基準に解決され、ベース URI は周りの $id から決まります。

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

final order = JsonSchema.parse(
  '{"\$id": "https://x.org/order.json",'
  ' "properties": {"to": {"\$ref": "address.json"}}}',
  registry: registry,
);
JsonSchemaRegistry 動作
JsonSchemaRegistry([schemas]) これらのスキーマを持つレジストリ
add(schema, {uri}) スキーマを uri で、なければその $id で追加します。どちらもなければ ArgumentError。同じ URI の後のスキーマが前のものを置き換えます
resolve(uri) uri で知られるスキーマ (フラグメントは無視)。その $id を持つサブスキーマも対象。なければ null
schemas 追加されたスキーマを URI ごとに (読み取り専用)

値に行き着かずにループする $ref は、永遠にたどられず、違反として報告されます。アプリケーションではレジストリは Bean です。JSON Schema の Bean を参照してください。

クラスのスキーマ

JsonSchemaGenerator は、@Introspected クラスのスキーマをそのイントロスペクションから、リフレクションなしで書き出します。スキーマは ObjectMapper が書き、読む JSON を表します。JSON 名 (@JsonProperty、@JsonNaming)、除外されたプロパティ (@JsonIgnore)、readOnly と writeOnly、そしてバリデーションの制約をキーワードとして含みます。

final generator = JsonSchemaGenerator();

generator.schemaOf(Order);      // 一つのクラス。使うクラスは $defs に入る
generator.schemasOf([Order]);   // クラス名ごと
generator.all();                // イントロスペクションされたすべてのクラス。名前ごと

schemaOf は、イントロスペクションされていないクラスに ArgumentError を投げます。all() は enum とジェネリッククラスを除き、同じ名前のクラスが二つあれば最初のものを残します。マッパーが lowerCamelCase 以外の命名戦略を使うなら、namingStrategy: を渡してください。

Dart スキーマ
String、int、double と num、bool string、integer、number、boolean
DateTime string、format は date-time
Duration string、format は duration
Uri string、format は uri-reference
BigInt 数字の文字列または整数
enum JSON の値 (@JsonValue も) を持つ enum
List、Set items を持つ array。Set は uniqueItems が加わる
Map additionalProperties を持つ object
イントロスペクションされたクラス #/$defs/<ClassName> への $ref。ルートのクラスは # なので循環も扱える
null 許容の型 その型または null
dynamic、Object、JsonNode 何でも

required には、マッパーが必要とするコンストラクター引数 (必須、null 非許容、読み取り専用でないもの) と、@NotNull を付けたプロパティが並びます。次の制約はキーワードになります。@NotEmpty、@NotBlank、@Size、@Min、@Max、@DecimalMin、@DecimalMax、@Positive、@PositiveOrZero、@Negative、@NegativeOrZero、@Matches (アンカーつき、フラグなし)、@Email、@Each (要素に対して) です。

記述されないもの: ポリモーフィズム (@JsonTypeInfo)、@JsonUnwrapped のプロパティ、独自の fromJson / toJson を持つクラス (任意の JSON)、日付と期間を数値で書くマッパーの設定。動作中のアプリケーションのこれらのスキーマは、Actuator の jsonschemas エンドポイント で見られます。

読むときの検査: @JsonSchemaSource

外から来て、公開されたスキーマがある JSON のクラスに @JsonSchemaSource を付けます。

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

ObjectMapper に schemaResolver があると、そのようなクラスのデコード済みの JSON を、オブジェクトを作る前にスキーマに照らして検査します。間違いがあると、すべての違反を列挙した JsonSchemaValidationException を投げます。

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

アプリケーションではリゾルバーを書く必要はありません。ObjectMapper の Bean には、@JsonSchemaSource と spring.json.schemas が指すスキーマを持つレジストリが渡されます (JSON Schema の Bean を参照)。ビルドはスキーマのクラスを、ルートのクラスに @JsonSchemaSource を付けて書き出すこともできます (JSON Schema のクラス を参照)。

対応するキーワード

グループ キーワード
型と値 type (リストも、integer も)、enum、const
オブジェクト properties、required、additionalProperties、patternProperties、propertyNames、minProperties、maxProperties、dependentRequired、dependentSchemas
配列 items、prefixItems、minItems、maxItems、uniqueItems、contains、minContains、maxContains
文字列 minLength、maxLength (Unicode のコードポイント単位)、pattern、format
数値 minimum、maximum、exclusiveMinimum、exclusiveMaximum、multipleOf
組み合わせ allOf、anyOf、oneOf、not、if / then / else
文書 $ref、$defs (と definitions)、$id、$anchor、スキーマ true と false

pattern は Unicode モードの Dart の RegExp で、アンカーされません。その他のキーワード (title、description、default、examples など) は無視されます。

フォーマット

フォーマット 有効な値
date-time RFC 3339。2026-01-31T12:00:00.5+02:00 (T と、オフセットまたは Z)
date 2026-01-31。実在する日
time 12:00:00Z。オフセットつき
email ローカル部、@、ドメイン。空白なし (RFC 5321 のすべての規則ではない)
uri スキームを持つ URI
uri-reference 任意の URI。相対でも可
uuid 8-4-4-4-12 の十六進数字
ipv4 先頭に 0 のない 0 から 255 までの四つの数
ipv6 Uri.parseIPv6Address が受け付けるもの

それ以外のフォーマットは無視され、文字列ではない値への format も無視されます。JsonSchemaFormats.isValid(format, value) で同じ検査を手で実行できます。

制限

Spring (Java) との対応

Spring には JSON Schema のサポートがありません。Java のアプリケーションはライブラリを使います。JSON の検査には networknt の json-schema-validator、クラスからスキーマを書くには Jackson の jsonSchema モジュールや victools の jsonschema-generator です。ここでは JsonSchema と JsonSchemaGenerator がその役割を果たします。@JsonSchemaSource と schemaResolver に相当するものはありません。

関連項目