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包
只需要三步,就可以使用。
安裝
- pubspec.yaml中引入
dev_dependencies:
json2entity: 1.0.6
- 激活:
$ pub global activate json2entity
- 添加
"$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