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 全家桶,真香。

相关推荐
stevenzqzq2 小时前
Android Jetpack Compose 列表开发指南:为什么你不需要再为底部 Item 写额外间距
android·android jetpack
撩得Android一次心动10 小时前
Jetpack Compose 知识点整理2【个人用】
android·笔记·学习·kotlin·compose
是真的小外套11 小时前
2024年软考中级信息安全工程师|选择题考点+案例分析真题解析(含答案)
android·网络
用户20187928316713 小时前
一文讲透 Android Native Heap 监控原理:一间"只进不出"的仓库,和总部派来的侦探
android
开心猴爷13 小时前
应对iOS审核4.3:可以使用 IpaGuard 来给属性名混淆的技术细节与平衡之道
后端·ios
iOS开发上架哦13 小时前
iOS应用耗电测试:使用Energy Log、Keymob和Instruments进行性能监控与能源消耗分析
后端·ios
YB137514 小时前
Jetpack Compose 动画animate*AsState
android
高晶14 小时前
Android 通讯录应用开发实战:从零搭建 SQLite 数据持久化完整项目
android·设计模式·前端框架
隐擎fox15 小时前
深入 Android 移动端风控与协议层对抗:内核级虚拟环境检测、网络堆栈特征伪装与住宅 IP 协同实战
android·网络·python·网络协议·tcp/ip
_瑞15 小时前
APM_KSCrash 原理
ios