json_model_mapper_gen

pub version GitHub stars

json_model_mapper_gen is a code generation library for Dart that generates boilerplate code for JSON serializable models using annotations.


๐Ÿ”ง Features

  • โœ… Generates model classes with:
    • Final fields
    • Constructors
    • fromJson and toMap methods
    • toString, ==, and hashCode overrides
  • โœ… Supports null-safety
  • โœ… Built on top of source_gen and build_runner

๐Ÿ“ฆ Installation

Add the following to your pubspec.yaml:

dependencies:
  json_model_mapper: ^0.0.1

dev_dependencies:
  build_runner: latest_version
  json_model_mapper_gen: latest_version

๐Ÿงช Example

Step 1: Create a file like user.dart

import 'package:json_model_mapper/json_model_mapper.dart';

@JsonModelMapper()
class User {
  int id;
  String name;
  String role;
  bool isActive;
  String? image;
}

Step 2: Run the build command

dart run build_runner build

๐Ÿ’ก For more build_runner commands, visit build_runner on pub.dev

After the build completes, a new file user_model.dart is generated.

  • Generated Output: user_model.dart
// GENERATED CODE - YOU CAN USE THIS CODE AS YOUR PROJECT CODE
// For issues, report to: product.vishalkaklotar@gmail.com

import 'dart:convert' show JsonEncoder;

class UserModel {
  final int id;
  final String name;
  final String role;
  final bool isActive;
  final String? image;

  const UserModel({
    required this.id,
    required this.name,
    required this.role,
    required this.isActive,
    this.image,
  });

  factory UserModel.fromJson(Map<String, dynamic> json) {
    int id = json['id'];
    String name = json['name'];
    String role = json['role'];
    bool isActive = json['isActive'];
    String? image = json['image'];

    return UserModel(
      id: id,
      name: name,
      role: role,
      isActive: isActive,
      image: image,
    );
  }

  Map<String, dynamic> toMap() {
    return {
      'id': id,
      'name': name,
      'role': role,
      'isActive': isActive,
      'image': image,
    };
  }

  @override
  String toString() => JsonEncoder.withIndent('	').convert(toMap());

  // Modify according requirement
  @override
  bool operator ==(Object other) {
    return identical(this, other) ||
        other is UserModel &&
            runtimeType == other.runtimeType &&
            id == other.id &&
            name == other.name &&
            role == other.role &&
            isActive == other.isActive &&
            image == other.image;
  }

  // Modify according requirement
  @override
  int get hashCode {
    return id.hashCode ^
    name.hashCode ^
    role.hashCode ^
    isActive.hashCode ^
    image.hashCode;
  }
}

๐Ÿ”ฅ Bonus

After generating the model file, you can even delete your original file user.dart. The output file is complete and ready to use on its own!