google / google/json_serializable.dart
Use @JsonConverter for map keys.
- Dominant language
- Dart
- Stars
- 1.6k
- Forks
- 461
- Avg merge
- 45m
- Merged PRs (30d)
- 1
Description
I have a `Map` whose key is a custom class. That class is is annotated with `@JsonConverter` for converting it to a String. When I run json_serializable over my code, I get the error
```
[project]: [SEVERE] json_serializable on lib/src/cart.dart:
[project]:
[project]: Could not generate `toJson` code for `items` because of type `Id`.
[project]: Map keys must be one of: Object, dynamic, enum, String, BigInt, DateTime, int, Uri.
```
Now `Id` is not one of those types, but by default it will serialise to a String. So should this use can be supported? More info/example below:
```shell
❯ dart --version
Dart SDK version: 3.2.5 (stable) (Tue Jan 16 15:02:13 2024 +0000) on "macos_arm64"
```
```dart
@JsonSerializable()
final class Cart {
final Map items;
}
@JsonSerializable()
@IdJsonConverter()
final class Id implements Comparable {
...
}
final class IdJsonConverter extends JsonConverter {
const IdJsonConverter();
@override
Id fromJson(String json) {
return Id.fromString(json);
}
@override
String toJson(Id object) {
return object.toString();
}
}
```
Map keys must be one of:
Contributor guide
Assessment
This issue has not been assessed yet.