关于 schemantic
Schemantic 是用于定义强类型数据类及可复用运行时 JSON Schema 的 Dart 库。它支持生成 JSON 转换与校验代码,可独立使用,也适用于 genkit-dart。
主要功能
- 01生成强类型数据类
- 02JSON 序列化与解析
- 03运行时访问 JSON Schema
- 04动态基础及集合 Schema
- 05联合与递归 Schema
适用场景
- 01将 JSON 解析为类型化 Dart 对象
- 02运行时校验任意 JSON
- 03在应用逻辑中复用 Schema
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ genkit-ai/ genkit-dart --skill schemantic安装后在 Claude Code 中输入/schemantic确认已加载。
详细介绍
Schemantic
Schemantic 是一个通用 Dart 库,用于定义强类型数据类,这些数据类会自动绑定到可重复使用的运行时 JSON schema。它是 genkit-dart 框架的标准库,也可以独立使用。
核心概念
需要强类型 JSON 解析或以编程方式验证 schema 时,始终使用 schemantic。
- 使用
@Schema()注解抽象类。 - 抽象 schema 类名使用
$前缀(例如,abstract class $User)。 - 始终运行
dart run build_runner build来生成.g.dartschema 文件。
基本用法
- 定义 schema:
import 'package:schemantic/schemantic.dart';
part 'my_file.g.dart'; // Must match the filename
@Schema()
abstract class $MyObj {
String get name;
$MySubObj get subObj;
}
@Schema()
abstract class $MySubObj {
String get foo;
}
- 使用生成的类:
构建器会创建一个具体类 MyObj(不带 $),其中包含一个工厂构造函数(MyObj.fromJson)和一个常规构造函数。
// Creating an instance
final obj = MyObj(name: 'test', subObj: MySubObj(foo: 'bar'));
// Serializing to JSON
print(obj.toJson());
// Parsing from JSON
final parsed = MyObj.fromJson({'name': 'test', 'subObj': {'foo': 'bar'}});
- 在运行时访问 schema:
生成的数据类具有一个静态 $schema 字段(类型为 SchemanticType<T>),可用于将定义传递给函数,或提取原始 JSON schema。
// Access JSON schema
final schema = MyObj.$schema.jsonSchema;
print(schema.toJson());
// Validate arbitrary JSON at runtime
final validationErrors = await schema.validate({'invalid': 'data'});
基本类型 Schema
不需要完整数据类时,Schemantic 提供了动态创建 schema 的函数。
final ageSchema = SchemanticType.integer(description: 'Age in years', minimum: 0);
final nameSchema = SchemanticType.string(minLength: 2);
final nothingSchema = SchemanticType.voidSchema();
final anySchema = SchemanticType.dynamicSchema();
final userSchema = SchemanticType.map(.string(), .integer()); // Map<String, int>
final tagsSchema = SchemanticType.list(.string()); // List<String>
联合类型(AnyOf)
若要让字段接受多种类型,请使用 @AnyOf。
@Schema()
abstract class $Poly {
@AnyOf([int, String, $MyObj])
Object? get id;
}
Schemantic 会生成一个专用辅助类(例如,PolyId)来处理这些值:
final poly1 = Poly(id: PolyId.int(123));
final poly2 = Poly(id: PolyId.string('abc'));
字段注解
你可以使用专用注解来设置更严格的验证边界:
@Schema()
abstract class $User {
@IntegerField(
name: 'years_old', // Change JSON key
description: 'Age of the user',
minimum: 0,
defaultValue: 18,
)
int? get age;
@StringField(
minLength: 2,
enumValues: ['user', 'admin'],
)
String get role;
}
递归 Schema
对于递归结构(例如树),必须在生成的 jsonSchema 属性中使用 useRefs: true。按常规方式定义即可:
@Schema()
abstract class $Node {
String get id;
List<$Node>? get children;
}
注意:Node.$schema.jsonSchema(useRefs: true) 会生成包含 JSON Schema $ref 的 schema。
评论
支持 Markdown