πŸ›  mg_tools

Pub Version Null Safety GitHub Stars


Tool to generate Dart models from .dto.json files using freezed and json_serializable.


πŸš€ Features

  • πŸ” Auto-scan project for all .dto.json files
  • πŸ“„ Supports targeting a single file
  • πŸ”„ Smart overwrite control using --replace
  • 🧩 Supports nested objects and nested lists
  • πŸ“† Auto-detect DateTime fields
  • πŸ”‘ Annotates with @JsonKey(name: "...", includeIfNull: false)
  • πŸ“ƒ Output all models in the same .dart file
  • πŸ“š Generates helper methods:
    • MyModel myModelFromJson(String str)
    • String myModelToJson(MyModel data)
    • or for list responses:
      • List<MyModel> myModelListFromJson(String str)
      • String myModelListToJson(List<MyModel> data)
  • 🐣 Clean, minimal, and fully ready for freezed & json_serializable

🧰 Getting started

  • Make sure you have the following dev dependencies in your pubspec.yaml:
dependencies:
  freezed_annotation:
  json_annotation:

dev_dependencies:
  mg_tools:
  build_runner:
  freezed:
  json_serializable:

Then run:

dart pub get

βš™οΈ Usage

βœ… Generate models from all .dto.json files

dart run mg_tools

πŸ” Force replace existing generated files

dart run mg_tools --replace

🎯 Generate model from a single file

dart run mg_tools user.dto.json

🎯 + πŸ” Replace single file if it exists

dart run mg_tools user.dto.json --replace

πŸ“ Example

Given a file named user.dto.json:

{
  "id": 1,
  "name": "John",
  "email": "john@example.com",
  "createdAt": "2024-03-20T12:00:00Z",
  "profile": {
    "avatar": "link"
  },
  "tags": ["dev", "dart"]
}

It generates a user.dart file like:

@freezed
class User with _$User {
  const factory User({
    @JsonKey(name: "id", includeIfNull: false) int? id,
    @JsonKey(name: "name", includeIfNull: false) String? name,
    @JsonKey(name: "email", includeIfNull: false) String? email,
    @JsonKey(name: "createdAt", includeIfNull: false) DateTime? createdAt,
    @JsonKey(name: "profile", includeIfNull: false) UserProfile? profile,
    @JsonKey(name: "tags", includeIfNull: false) List<String>? tags,
  }) = _User;

  factory User.fromJson(Map<String, dynamic> json) => _$UserFromJson(json);
}

πŸ’‘ Tips

πŸ“£ Contribute

Feel free to open an issue or submit a PR with improvements, features, or bug fixes πŸš€


πŸ“„ License

MIT

Libraries