json2dartgen 1.1.0
json2dartgen: ^1.1.0 copied to clipboard
A CLI tool to generate Dart models from JSON, with json_serializable support and copyWith methods.
json2dartgen #
A CLI tool to generate Dart model classes from JSON. Supports json_serializable
, copyWith
, and optional snake_case → camelCase conversion.
Features #
- Automatically generate Dart classes from any JSON file
json_serializable
compatible (fromJson
/toJson
)- Generates
copyWith
method - Optional snake_case → camelCase conversion
- Output as separate
.dart
files - Configurable output directory
- CLI help included
Getting Started #
Install #
Activate globally via Dart:
dart pub global activate json2dartgen
Usage #
dart run json2dartgen <input.json> [options]
Options:
Flag | Description |
---|---|
-c, --camel-case |
Convert snake_case JSON keys to camelCase field names |
-o, --output-dir |
Output directory for .dart files (default: current directory) |
-n, --nullable-copywith |
Generate nullable copyWith method with ability to null non-nullables |
-h, --help |
Show usage instructions |
Examples #
Generate models in the current directory:
dart run json2dartgen api_response.json
Generate models with camelCase fields:
dart run json2dartgen api_response.json --camel-case
Generate models in a specific directory:
dart run json2dartgen api_response.json --camel-case --output-dir lib/models
Generated Code 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);
}
Notes #
- Ensure
json_annotation
andjson_serializable
are in yourpubspec.yaml
dependencies for Flutter/Dart projects. - Run
build_runner
to generate the.g.dart
files:
dart run build_runner build --delete-conflicting-outputs
License #
This project is licensed under the MIT License - see the LICENSE file for details.
Author #
Saleh Talebizadeh https://salehtz.ir