Skip to content

Use the extension methods feature to remove need of most boilerplate #558

Closed

Description

Starting with Dart 2.6, json_serializable has the option to create the toJson() method for the user. Although extension methods don't support constructors, json_serializable could create a static generative method instead. This means that user code would look like this:

import 'package:json_annotation/json_annotation.dart';

part 'example.g.dart';

@JsonSerializable(nullable: false)
class Person {
  final String firstName;
  final String lastName;
  final DateTime dateOfBirth;
  Person({this.firstName, this.lastName, this.dateOfBirth});
}

The generated extension might look like this:

// in example.g.dart

extension on Person {
  static Person fromJson(Map<String, dynamic> json) => _$PersonFromJson(json);

  Map<String, dynamic> toJson() => _$PersonToJson(this);
}

// ...

Rest of the code can keep the same.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions