Flutter JsonToDart 支持 JsonSchema

前言

JSON Schema 是一种用于描述和验证 JSON 文档结构的规范。它提供了一个强大的工具集,用于定义 JSON 数据的格式、类型和约束。

关键点:

  • 定义了用于描述 JSON 文档结构的语法。

  • 支持多种数据类型和约束,包括字符串、数字、布尔值、对象、数组等。

  • 提供了验证机制,确保 JSON 数据符合预定义的结构和规则。

在实际开发中,很多时候,我们没法方便地直接获取到接口的 Json ,但是后端文档里面一般都会提供 JSON Schema。

JsonToDart

fluttercandies/json_to_dart_library: json_to_dart_library 该库已经支持解析 JSON Schema ,代码在后面。

Yapi API

YMFE/yapi: YApi 是一个可本地部署的、打通前后端及QA的、可视化的接口管理平台

没有现成的,根据 api 实现了一套 dart 版本的

fluttercandies/yapi_api: A Dart package for interacting with YApi server APIs. Provides easy-to-use methods to fetch interface and project data from YApi with proper authentication and error handling.

快速上手

安装依赖

bash 复制代码
flutter pub add json_to_dart_library

如需配合 YApi 使用:

bash 复制代码
flutter pub add yapi_api

基本用法

通过 JSON Schema 生成 Dart Model

假设你有如下 JSON Schema:

json 复制代码
{
  "$schema": "http://json-schema.org/draft-07/schema#",
  "title": "User",
  "type": "object",
  "properties": {
    "id": { "type": "integer", "description": "用户ID" },
    "name": { "type": "string", "description": "用户名" },
    "email": { "type": "string", "description": "邮箱" }
  },
  "required": ["id", "name"]
}

你可以这样生成 Dart 代码:

dart 复制代码
import 'package:json_to_dart_library/json_to_dart_library.dart';

void main() async {
  DartObject? dartObject = await jsonToDartController.jsonToDartObject(
    json: '''{
  "\$schema": "http://json-schema.org/draft-07/schema#",
  "title": "User",
  "type": "object",
  "properties": {
    "id": { "type": "integer", "description": "用户ID" },
    "name": { "type": "string", "description": "用户名" },
    "email": { "type": "string", "description": "邮箱" }
  },
  "required": ["id", "name"]
}''',
  );

  var errors = jsonToDartController.getErrors();
  if (errors.isNotEmpty) {
    print('Errors found:');
    for (var error in errors) {
      print(error);
    }
    return;
  }

  if (dartObject != null) {
    var dartCode = jsonToDartController.generateDartCode(dartObject);
    File('output.dart').writeAsStringSync(dartCode!);
    print('Dart code generated successfully:');
  }  
}

结合 YApi 自动拉取接口 Schema 并生成 Dart Model

dart 复制代码
import 'package:yapi_api/yapi_api.dart';
import 'package:json_to_dart_library/json_to_dart_library.dart';

void main() async {
  YapiLoginResponse? loginResponse =
      await apiHelper.login(email: '', password: '');
  if (loginResponse != null && loginResponse.errcode == 0) {
    print('login success');
  } else {
    print('login failed : ${loginResponse?.errmsg}');
    return;
  }
  YapiInterfaceResponse? interfaceResponse = await apiHelper.getInterface(1);
  if (interfaceResponse != null) {
    print('interface : ${interfaceResponse.data?.title}');
  } else {
    print('get interface failed ');
  }
  YapiInterface? interfaceData = interfaceResponse?.data;
  if(interfaceData?.resBodyIsJsonSchema == true){
    final String? schema = interfaceData.resBody;
    final DartObject? result = await jsonToDartController.jsonToDartObject(schema);
     
  }
}

客户端使用

当然我们也提供了客户端

结语

最后感谢 龙哥/alex 帮忙弄的 action,现在打包 web 和桌面端都一步到位。 需要的自提 release.yml。

爱 Flutter,爱糖果,欢迎加入Flutter Candies,一起生产可爱的Flutter小糖果

最最后放上 Flutter Candies 全家桶,真香。

相关推荐
千里马学框架5 天前
一起学 Android 14:ShellTransition 屏幕旋转过程深度剖析
android·智能手机·性能优化·framework·性能·屏幕旋转·rotation
美狐美颜SDK开放平台5 天前
开发直播APP时如何接入视频美颜SDK?开发流程与注意事项
android·人工智能·计算机视觉·音视频·直播美颜sdk
AFinalStone5 天前
Android7 SystemUI源码解析(七)Keyguard锁屏模块深度解析
android·systemui
致远ccc5 天前
Google Play 上架前如何测试 App?多国家 Android 环境测试
android·app测试·googleplay·多国家应用测试
ttyyttemo5 天前
Kotlin 协程中的 Job 结构化并发与取消
android
sun0077005 天前
tbox 4g/5g切换,导致wan ip 改变,导致车机旧网络不可用。需要重启车机才行
android
其实防守也摸鱼5 天前
内网穿透与反向代理:原理、工具与实战指南
android·大数据·运维·安全·网络安全·自动化·渗透
茶底世界之下5 天前
为什么预览、录制、离线导出不能共享同一个背压策略?
ios·swift
AFinalStone5 天前
Android7 SystemUI 源码解析(四)NavigationBar 导航栏与 SystemBars
android·systemui
JMchen5 天前
属性动画原理与高级动画实现
android·kotlin·canvas