告别手写,自动生成Flutter/Dart实体类

2 篇文章 0 订阅
1 篇文章 0 订阅

json2entity

告别手写,自动生成Flutter/Dart实体类。

在Java中,json转实体类,有很多工具,我一般用IDEA的Gsonformat插件,把json字符串粘贴到输入框,点击生成,一个Java Bean就写好了。
json2entity,就是Dart和Flutter开发的Gsonformat。

最简用法

$ j2e -j '{"result":1,"msg":"ok"}'

输出:

$ j2e -j '{"result":1,"msg":"ok"}'
class Model {
 num result;
 String msg;
 Model({
  this.result,
  this.msg
 });

 Model.fromJson(Map < String, dynamic > json):
  result=json['result'],
  msg=json['msg'];
 Map <String, dynamic> toJson() => {
  'result':result,
  'msg':msg
 };
}%

怎么样是不是很简单?

BUT. 哪里下载j2e?
j2e 只是json2entity 的别名,json2entity 和 j2e, 使用哪个都可以,是一个dart包
只需要三步,就可以使用。

安装

  1. pubspec.yaml中引入
dev_dependencies:
  json2entity: 1.0.6
  1. 激活:
$ pub global activate json2entity
  1. 添加"$HOME/.pub-cache/bin"到你的PATH变量中

设置完成后,在你的terminal中输入j2e回车,看看效果吧:

$ j2e
No input args found
Usage:
        -j, --json                              Input json string
        -f, --file                              Input json from file
        -o, --output                            Input output file path and name
        -v, --[no-]verbose                      Show verbose
        -s, --[no-]json-serializable-support    Indicates whether json-serializable is supported
        -h, --[no-]help                         Help%

如果输出如上所示,则已经成功了。

高级用法

输出到文件

上面给出了最简单用法,但是似乎不够智能,还得ctrl-c/ctrl-v
如果你想输出到文件,也是ok的。你可以使用重定向,但是有更好的方法,
使用-o选项,这样做的好处是,既指定了文件名,又指定了类名:
j2e -j '{"result":1,"msg":"ok"}' -o lib/model/BaseModel

$ j2e -j '{"result":1,"msg":"ok"}' -o lib/model/BaseModel
$ cat lib/model/base_model.dart
class BaseModel {
 num result;
 String msg;
 BaseModel({
  this.result,
  this.msg
 });

 BaseModel.fromJson(Map < String, dynamic > json):
  result=json['result'],
  msg=json['msg'];
 Map <String, dynamic> toJson() => {
  'result':result,
  'msg':msg
 };
}
支持json_serializable

如果你使用了json_serializable. 也是可以的:只需要多一个-s

$ j2e -j '{"result":1,"msg":"ok"}' -s
$ j2e -j '{"result":1,"msg":"ok"}' -o lib/model/BaseModel

当然,这种情况下,生成的只是部分代码,.g.dart还需要你手动的执行一下builder:

$ flutter packages pub run build_runner build
从文件读取输入

通过-j从命令行读取输入,每次只能读取一条json。如果不能满足你的需求,你可以使用-f
从文件批量读取并装换。
文件的格式,必须是格式良好的json,例如:

//input.json
{
    “BaseModel": "{\"result\":1,\"msg\":\"ok\"}",
    "AnswerModel": "{\"result\":1,\"msg\":\"ok\",\"data\":{\"answer\":\"A\"}}"
}

j2e -f input.json -o lib/model
or
j2e -f input.json -o lib/model -s

对于一个工具来说,当然是越简洁越好,上面的功能,已经基本可以。
代码已经打包发布到pub仓库了,名字就叫json2entity

更多信息,在Github

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值