flutter如何通过jsontodart支持jsonschema

在Flutter开发中,使用json_serializable生成Dart模型时,能否直接支持JSON Schema规范?目前通过jsonToDart工具转换时,主要依赖JSON样本数据,但项目需要根据Schema定义更严格的类型校验(如字段必填、枚举值限制等)。是否有现成的方案或插件能在生成Dart代码时自动集成Schema验证逻辑?或者需要手动编写扩展验证逻辑?

2 回复

Flutter中,json_serializable不支持JSON Schema。可使用json_schema包验证数据,结合json_annotation手动定义模型。步骤:1. 添加依赖;2. 创建Dart类;3. 用json_schema验证输入数据。

更多关于flutter如何通过jsontodart支持jsonschema的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


在Flutter中,通过 json_serializable 包可以生成类型安全的模型类,但原生不支持 JSON Schema。以下是实现方案:

1. 使用第三方工具转换

  • 在线工具:将 JSON Schema 转换为 Dart 类(如 quicktype.io
  • 手动依据 Schema 定义编写 Dart 类

2. 自定义验证(推荐)

import 'package:json_annotation/json_annotation.dart';

part 'user.g.dart';

@JsonSerializable()
class User {
  final String name;
  final int age;

  User({required this.name, required this.age});

  // 从JSON生成实例
  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);

  // 转换为JSON
  Map<String, dynamic> toJson() => _$UserToJson(this);

  // 自定义验证方法
  void validate() {
    if (name.isEmpty) throw ArgumentError('Name cannot be empty');
    if (age < 0) throw ArgumentError('Age must be non-negative');
  }
}

3. 使用校验包增强 添加 json_schema 依赖:

dependencies:
  json_schema: ^2.2.0

示例用法:

import 'package:json_schema/json_schema.dart';

void validateUser(Map<String, dynamic> json) async {
  final schema = {
    "type": "object",
    "properties": {
      "name": {"type": "string"},
      "age": {"type": "integer", "minimum": 0}
    }
  };
  
  final validator = await JsonSchema.createSchema(schema);
  final errors = validator.validate(json);
  if (errors.isNotEmpty) throw FormatException(errors.join(', '));
}

步骤总结

  1. 用工具将 JSON Schema 转为 Dart 类结构
  2. 通过 json_serializable 生成序列化代码
  3. 结合 json_schema 包或自定义方法实现数据验证

此方案在保持类型安全的同时,实现了类似 JSON Schema 的验证能力。

回到顶部