json2entity

A tool to automatically generate Flutter/Dart entity classes (source files)

Please bear with me for my first post.

In Java development, JSON string to entity class, there are many tools, I most commonly used IDEA Gsonformat plug-in, paste JSON string into the text box, click generate, a Java Bean will be written. Json2entity, the Gsonformat developed by Dart and Flutter.

The simplest usage

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

Terminal output:

$ 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 }; } %Copy the code

Isn’t that easy?

BUT!!! What is J2E? Where is J2E?

J2e is just an alias for JSON2Entity, which is equivalent to J2E using JSON2Entity. Json2entity is a Dart package, and here’s how to install it.

Preparation before use

Take up to 3 steps:

  1. Pubspec. Introduced in yaml
dev_dependencies:
  json2entity: ^ 1.1.2
Copy the code
  1. Activation:
$ pub global activate json2entity
Copy the code
  1. Make sure that"$HOME/.pub-cache/bin"Added to your PATH variable. If yes, skip this step.

Enter J2E or jSON2Entity in your Terminal and press Enter to see what it looks like:

$ 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%
Copy the code

If the output looks like this, you’ve succeeded, and you can happily use any path in Terminal.

Advanced usage

Output to file

No output is specified, default output to the terminal.

If you want to export to a file, you can use the -o option, or you can use redirection to export to a file. Using -o, the following arguments will be the filename and class name:

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
 };
}
Copy the code

Note, for example, that BaseModel is humped so that the entity class name is changed to the underscore: base_model.dart.

Support json_serializable

If you use jSON_serializable. That’s ok: just add -s

$ j2e -j '{"result":1,"msg":"ok"}' -s                           Output to stdout
$ j2e -j '{"result":1,"msg":"ok"}' -o lib/model/BaseModel -s    Dart./lib/base_model.dart
Copy the code

Of course, in this case, only part of the code is generated, the corresponding.g.art file, and you need to manually execute build_runner:

$ flutter packages pub run build_runner build
Copy the code

Or:

$ flutter packages pub run build_runner watch
Copy the code

Read input from a file

-j reads input from the command line, one JSON at a time. If your requirements are not met, you can use -f to batch read and convert from the file. The format of the input file must be a well-formed JSON string in the following format:

/ / input. Json {" BaseModel ":" {\ "result \" : 1, \ "MSG \" : \ "ok \"} ", "AnswerModel" : "{\"result\":1,\"msg\":\"ok\",\"data\":{\"answer\":\"A\"}}" }Copy the code

-f specifies the input file and -o specifies the output directory. Run the following command:

$ j2e -f input.json -o lib/model
$ j2e -f input.json -o lib/model -s
Copy the code

Lowercase hump field support

What if key is underlined and you want the entity-class field to be humped? If you use jSON_serializable, you can use the @jsonKey annotation, for example:

@JsonKey(name: 'registration_date_millis')
final int registrationDateMillis;
Copy the code

Version 1.1.0+ already supports autocompletion of @jsonkey by adding a -c option to -s:

$ j2e -j '{"result":1,"error_msg":"ok"}' -sc
import 'package:json_annotation/json_annotation.dart';
part 'model.g.dart';

@JsonSerializable()
class Model {
  num result;
  @JsonKey(name: 'error_msg')
  String errorMsg;
  Model({
    this.result,
    this.errorMsg
  });

  factory Model.fromJson(Map<String, dynamic> json) => _$ModelFromJson(json);
  Map<String, dynamic> toJson() => _$ModelToJson(this);
}
Copy the code

Also: The project provides a separate tool, Camelize, that automatically lowers the underlined fields of the existing Dart entity class to lowercase camel style and adds @jsonKey.

camelize <dart_file_path>
Copy the code

other

The tool provides simple indentation and does not guarantee perfect indentation. You can use DartfMT to format yourself after generation:

dartfmt -w <dart-code-path>
Copy the code

Or use an IDE to format your code.

For a tool, that’s all you need. I originally planned to write an IDEA plugin, but gave it up after using vscode. And it’s better to use terminal, right?

For more examples, head over to my Github.

Json2entity Dart language implementation, has been published to the Pub | Dart | json2entity.