# dart_bean **Repository Path**: DonaldDu/dart_bean ## Basic Information - **Project Name**: dart_bean - **Description**: dart to part helper, json to dart bean - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2023-01-30 - **Last Updated**: 2023-03-07 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # 用Dart写的DartBean秒速生成器 # 项目缘由 之前开发时,用的FlutterJsonBeanFactory,确实非常好用。 也遇到一些问题 * 有时,会引入一些无用的类,却不能清理,有强迫症的太难受了。 * 一行定义多个变量时,无法正确识别。 * 日期类型不能全局自定义。 * 不支持把接口字段解析到私有变量。 * 枚举支持不太方便。 * 不支持纯Dart项目(非Flutter项目) # 使用.Part 来实现Bean功能感觉简洁很多。 用户原始代码 ```dart @JsonSerializable() class UserCompany { late String name; late String catchPhrase; late String bs; } ``` 自动补全后的用户代码 ```dart @JsonSerializable() class UserCompany { late String name; late String catchPhrase; late String bs; static UserCompany fromJson(dynamic json) => _$UserCompanyFromJson(json); Map toJson() => _$UserCompanyToJson(this); } ``` 生成的 .part 文件 ```dart UserCompany _$UserCompanyFromJson(Map json) { final it = UserCompany(); it.name = $JSON.convert(json['name']) ?? it.name; it.catchPhrase = $JSON.convert(json['catchPhrase']) ?? it.catchPhrase; it.bs = $JSON.convert(json['bs']) ?? it.bs; return it; } Map _$UserCompanyToJson(UserCompany it) => { 'name': it.name, 'catchPhrase': it.catchPhrase, 'bs': it.bs, }; ``` # 特性说明 * 支持为纯字段的Bean生成辅助方法,并引入依赖。 * 支持JsonField注解 * 兼容官方JsonKey部分功能(name, ignore, includeToJson, includeFromJson) * 支持枚举(配合JsonValue使用) * 支持自定义的JsonConverter * 支持全局配置基本类型解析(包括DateTime) * 支持全局配置和当前项目配置,项目中的缺省项继承全局配置 * 支持基本类型 全局默认值设定 ### 特性:支持JsonField注解 使用 JsonField或(官方json_annotation)JsonKey 注解可把接口字段解析到类的私有变量上。 > 手写Bean时,可以先通过快捷键执行一次自动生成代码的程序,生成注解等辅助类,以便使用IDE的依赖智能导入功能。 ``` @JsonSerializable() class JsonFieldFeature { @JsonField(name: 'a') String? _a; } ``` ### 特性:支持自定义的JsonConverter ``` @JsonSerializable() class CustomJsonConverterBean { @SmartBool() bool? b; @SmartBoolList() List? b2; } class SmartBool extends JsonConverter { const SmartBool(); @override bool? fromJson(dynamic json) { if (json == null) return null; final v = json.toString().toLowerCase(); if (v == '1') return true; // 0/1 if (v == 'y') return true; // Y/N return v == 'true'; } @override dynamic toJson(bool? v) { if (v == null) return null; return v ? 'Y' : 'N'; } } class SmartBoolList extends JsonConverter?, dynamic> { const SmartBoolList(); @override List? fromJson(dynamic json) { final v = json as String?; return v?.split(',').map((e) => SmartBool().fromJson(e)!).toList(); } @override dynamic toJson(List? v) { if (v == null) return null; return v.map((e) => SmartBool().toJson(e)).join(','); } } ``` ### 特性:支持枚举(配合JsonValue使用) 使用JsonValue注解指定枚举解析值, **特别说明:接口返回值类型,须与代码中完全一样** 如下代码所示 返回int数值1时,解析结果为Feature.high。 返回字符串1时,解析结果为Feature.low。 ``` @JsonSerializable() class EnumFeatureBean { Feature? e; List? e2; List? e3; } enum Feature { ///高峰 @JsonValue(1) high, ///低峰 @JsonValue('1') low, ///平峰 @JsonValue('M') major; const Feature(); } ``` ### 特性:支持全局配置基本类型解析(包括DateTime) ``` @JsonSerializable() class BuildInJsonConverterBean { int intA = 1; bool boolB = false; List? b2; List? b3; String stringC = '1'; double doubleD = 0.0; DateTime? dateTime; List? dateTime2; Map? map; } DateTime? defaultDateTimeFromJson(dynamic v) { final millisecondsSinceEpoch = int.parse(v.toString()); return DateTime.fromMillisecondsSinceEpoch(millisecondsSinceEpoch); } dynamic defaultDateTimeToJson(DateTime? v) { return v?.millisecondsSinceEpoch; } //全局初始化,应用自定义类型转换器 $JSON.addDefaultFromJson(defaultDateTimeFromJson); $JSON.addDefaultToJson(defaultDateTimeToJson); ``` ### 特性:支持全局配置和当前项目配置 基本兼容FlutterJsonBeanFactory的JsonField注解,不支持isEnum特性。 # 用户配置 > .json_bean.toml ``` #TOML https://toml.io/cn/ #genDirName = 'gen' #clickableFileLink = false #ignoreOfficialBean = true #flattenBean = false #autoDefaultValueStyle = false #jsonSupportFileName = 'json_support.dart' #jsonCastFileName = 'json_cast.dart' #jsonCastParamName = '$JSON' #fromJsonParamName = 'json' #toJsonParamName = 'it' #fromJsonType = 'static' #dartFormatterPageWidth = 160 ``` 配置文件格式须为 [TOML](https://toml.io/cn/) ## 当前项目配置 执行命令后,会在当前项目下生成一个(.json\_bean.toml)配置文件,包含当前使用的默认配置值,配置为注释状态,可取消注释以调整值。 ## 全局配置 请在系统的环境变量中配置 JSON\_BEAN\_CONFIG=全路径配置文件地址 Platform.environment['JSON_BEAN_CONFIG'] <- full path of xx_json_bean.toml; ## 配置项说明 ```dart /// the name of dir stored all generated files @JsonKey(defaultValue: 'gen') late String genDirName; ///full file path or not in console log
/// 'my_project/lib/bean.dart' <- clickable then navigate to source code
/// 'bean.dart' <- not clickable @JsonKey(defaultValue: false) late bool clickableFileLink; ///OfficialBean: file.contains("part 'file_name.g.dart';")
///use json_serializable for unsupported feature of dart_bean @JsonKey(defaultValue: true) late bool ignoreOfficialBean; ///when json2bean, add beanName to Json child bean as prefix or not
@JsonKey(defaultValue: true) late bool flattenBean; ///support parse null json to default value or not.
///eg: late int a; when null json, a=0; @JsonKey(defaultValue: false) late bool autoDefaultValueEnable; @JsonKey(defaultValue: 'json_support.dart') late String jsonSupportFileName; @JsonKey(defaultValue: 'json_cast.dart') late String jsonCastFileName; @JsonKey(defaultValue: r'$JSON') late String jsonCastParamName; @JsonKey(defaultValue: 'json') late String fromJsonParamName; @JsonKey(defaultValue: 'it') late String toJsonParamName; ///fromJson method style 'static' or 'factory' @JsonKey(defaultValue: 'static') late String fromJsonType; ///line width for generated files @JsonKey(defaultValue: 160) late int dartFormatterPageWidth; ``` # 更多信息,请参考测试用例。 * /test/feature\_test.dart * /test/gen\_test.dart # 常见问题 ## 基本类型全局默认值设定 通过Json自动生成的Bean文件,所有非空变量默认为late。用户可以根据情况手动调整为可空的,或设定一个默认值。 还可以不做调整,但启用全局默认值功能,启用方式如下: > 配置 autoDefaultValueStyle = true #默认为false 用户定义变量时,可申明默认值,申明式默认值优先级高于全局默认值。 **自定义JsonConverter来解析List变量时,C无法获取到正确类型。** ```dart //$DefaultJSONConvert只是JSONConvert的默认实现,用户可自定义实现,然后赋值给$JSON就行。 //$nullDefaultFromJson只是默认的实现,用户可自行修改方法实现,以满足业务需求。 $DefaultJSONConvert.nullDefaultFromJson = $nullDefaultFromJson; dynamic $nullDefaultFromJson(bool? buildDefaultValue) { if (buildDefaultValue == false) return null; if (M == List) return [];//自定义JsonConverter来解析List变量时,C无法获取到正确类型。 if (M == Map) return {}; final type = M.toString(); switch (type) { case 'int': return 0; case 'bool': return false; case 'double': return 0.0; case 'String': return ''; } return null; } ``` # 使用方法 把当前项目代码拉到本地,切换到代码bin目录,通过以下命令编译,(windows)得到 json_bean.exe dart compile exe json_bean.dart >dart compile exe 编译输出能在当前操作系统上运行。 支持所有系统 win/Linux/mac等,windows上编译出的文件名后缀是 .exe,其它平台没试过 更多信息,请查看官方文档 [dart-compile](https://dart.cn/tools/dart-compile) 在ExternalTools中配置两个外部插件 ![dart2part.png](https://p3-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/f4373a2759e0492bb54cada97ef4a115\~tplv-k3u1fbpfcp-watermark.image?) ![json2bean.png](https://p1-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/3acb0e0ded1242debf6d0bdb0da011a1\~tplv-k3u1fbpfcp-watermark.image?) 触发Json2Bean时,会弹出一个输入框,用户需要输入参数 beanName ``` bean name(include path relative to libDir) for json2bean, eg:'data/user_info' -> lib/data/user_info.dart root bean -> class UserInfo{} ``` 给ExternalTools中配置的外部插件指定快捷键 ![shortcut.png](https://p6-juejin.byteimg.com/tos-cn-i-k3u1fbpfcp/1b34fb6576eb40218cb60ef21d81781a\~tplv-k3u1fbpfcp-watermark.image?)