google / google/json_serializable.dart

[bug] `json_serializable` is unable to handle enum with generics

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

Description

Hello there.

Try this out:
```dart
import 'package:json_annotation/json_annotation.dart';

part 'asdlol_dto.g.dart';

enum Slug {
asd(),
lol(),
rofl(),
lmao<(int, int)>();

const Slug();
}

@JsonSerializable()
class Serializable {
const Serializable(this.slug);
final Slug slug;
}
```

JsonSerializable generates this code:
```dart
// GENERATED CODE - DO NOT MODIFY BY HAND

part of 'asdlol_dto.dart';

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

Serializable _$SerializableFromJson(Map json) =>
$checkedCreate('Serializable', json, ($checkedConvert) {
final val = Serializable(
$checkedConvert('slug', (v) => $enumDecode(_$SlugEnumMap, v)),
);
return val;
});

Map _$SerializableToJson(Serializable instance) =>
{'slug': _$SlugEnumMap[instance.slug]!};

const _$SlugEnumMap = {
Slug.asd: 'asd',
Slug.lol: 'lol',
Slug.rofl: 'rofl',
Slug.lmao: 'lmao',
};
```

But the above errors at analysis time, since `_$SlugEnumMap` is incorrectly typed.
```
The argument type 'Map, String>' can't be assigned to the parameter type 'Map, String>'. [[argument_type_not_assignable](https://dart.dev/tools/diagnostics/argument_type_not_assignable?utm_source=dartdev&utm_medium=redir&utm_id=diagcode&utm_content=argument_type_not_assignable)]
```

I'm not sure what I can do on my end to fix of even to circumvent this.

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.