Skip to main content

Introducing json2dartgen: Generate Dart Models from JSON Effortlessly ๐Ÿš€

·349 words·2 mins
Alex Tz
Author
Alex Tz
Flutter developer, open-source contributor, tech blogger

I’m excited to announce the release of json2dartgen โ€” a brand new CLI tool to make working with JSON in Dart and Flutter projects much easier.


Why json2dartgen?
#

If youโ€™ve ever worked with APIs in Flutter, you know the pain: you get a massive JSON response, and now you need Dart models with fromJson, toJson, and maybe a copyWith method too. Tools like quicktype.io are great, but they often struggle with very large JSONs or donโ€™t quite integrate with your code style.

Thatโ€™s why I built json2dartgen:

  • Works directly from the command line
  • Handles large JSON files with ease
  • Fully supports json_serializable
  • Generates clean, idiomatic Dart code

Features
#

  • โœ… fromJson / toJson using json_serializable
  • โœ… Automatic copyWith generation
  • โœ… Optional snake_case โ†’ camelCase conversion
  • โœ… Output models as a single file or multiple files
  • โœ… Configurable via CLI flags
  • โœ… Lightweight, fast, and built for Dart devs

Installation
#

Install globally via Dart:

dart pub global activate json2dartgen

Usage
#

json2dartgen <input.json> [options]

Options
#

FlagDescription
-c, --camel-caseConvert snake_case JSON keys to camelCase field names
-o, --output-dirOutput directory for .dart files (default: current directory)
-h, --helpShow usage instructions

Example
#

Input JSON:

{
  "building_id": 1130,
  "floor_count": 5,
  "location_name": "North Wing"
}

Generated Dart model:

import 'package:json_annotation/json_annotation.dart';

part 'root.g.dart';

@JsonSerializable()
class Root {
  @JsonKey(name: 'building_id')
  final int buildingId;

  @JsonKey(name: 'floor_count')
  final int floorCount;

  @JsonKey(name: 'location_name')
  final String locationName;

  const Root({
    required this.buildingId,
    required this.floorCount,
    required this.locationName,
  });

  Root copyWith({
    int? buildingId,
    int? floorCount,
    String? locationName,
  }) {
    return Root(
      buildingId: buildingId ?? this.buildingId,
      floorCount: floorCount ?? this.floorCount,
      locationName: locationName ?? this.locationName,
    );
  }

  factory Root.fromJson(Map<String, dynamic> json) => _$RootFromJson(json);
  Map<String, dynamic> toJson() => _$RootToJson(this);
}

Try It Out
#

You can get started right now:

dart pub global activate json2dartgen
json2dartgen your_api_response.json --camel-case --output-dir lib/models

Whatโ€™s Next?
#

This is just the beginning ๐Ÿš€. Future updates will include:

  • More configuration options
  • Better error messages
  • Improved type inference
  • Flutter-specific utilities

If you try it out, Iโ€™d love to hear your feedback and feature requests.

๐Ÿ‘‰ Check it out here: json2dartgen on pub.dev

Happy coding! ๐Ÿ’™