google / google/json_serializable.dart

[Suggestion] Rework Enum management

Open
#1,538 2 comments 4 reactions 0 assignees View on GitHub
Dominant language
Dart
Stars
1.6k
Forks
461
Avg merge
45m
Merged PRs (30d)
1

Description

Take this example :

```dart
import 'package:freezed_annotation/freezed_annotation.dart';

part 'example.g.dart';

enum ExampleType { one, two, three }

@JsonSerializable()
class Example {
final ExampleType type;
final String name;

Example({
required this.type,
required this.name,
});

factory Example.fromJson(Map json) => _$ExampleFromJson(json);

Map toJson() => _$ExampleToJson(this);
}
```

Once generated we got :

```dart
// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'example.dart';

// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************

Example _$ExampleFromJson(Map json) => Example(
type: $enumDecode(_$ExampleTypeEnumMap, json['type']),
name: json['name'] as String,
);

Map _$ExampleToJson(Example instance) => {
'type': _$ExampleTypeEnumMap[instance.type]!,
'name': instance.name,
};

const _$ExampleTypeEnumMap = {
ExampleType.one: 'one',
ExampleType.two: 'two',
ExampleType.three: 'three',
};
```

Json_serializable generates a hard-coded enum ↔ string map in the .g.dart file (e.g. _$ExampleTypeEnumMap). This duplicates information that already exists on the enum itself (Enum.values / Enum.name).

This can be error-prone, especially when the enum comes from an external package (ex: pub.dev, monorepo, ...). If that package updates the enum and build_runner is not re-run, the generated map becomes out of sync with the actual enum definition, potentially leading to errors.

Since enums already expose their values and names, it seems possible to rely on them instead of generating and maintaining a separate hard-coded map.

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.