google / google/json_serializable.dart

Map with enum keys is serialized as List, but deserialized as Map

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

Description

Just had some fun figuring out why this fails:

```dart
import 'package:equatable/equatable.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:json_annotation/json_annotation.dart';

part 'enum.g.dart';

enum A { a, b }

@JsonSerializable(anyMap: true, explicitToJson: true)
class B extends Equatable {
final Map map;

Iterable get values => map.values;

const B([Map? values]) : map = values ?? const {A.a: 1, A.b: 2};

B update(A a, int value) {
return B(Map.from(map)..[a] = value);
}

factory B.fromJson(Map json) {
return _$BFromJson(json);
}

Map toJson() => _$BToJson(this);

@override
List get props => map.values.toList();
}

void main() {
test('description', () {
final instance = const B().update(A.a, 3);
expect(B.fromJson(instance.toJson()), equals(instance));
});
}

```

Having a getter with the same name as a constructor parameter leads to _that_ one's values being serialized rather than the actual field. It would be great to

- ideally have this not compile without explicitly making it,
- generate a warning during build runner,
- maybe reflect this somewhere on the pub page? I might have missed it but at least the word "getter" is not present.

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.