Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use @JsonConverter for map keys. #1393

Open
bramp opened this issue Jan 24, 2024 · 1 comment
Open

Use @JsonConverter for map keys. #1393

bramp opened this issue Jan 24, 2024 · 1 comment

Comments

@bramp
Copy link

bramp commented Jan 24, 2024

I have a Map<Id, int> 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:

❯ dart --version
Dart SDK version: 3.2.5 (stable) (Tue Jan 16 15:02:13 2024 +0000) on "macos_arm64"
@JsonSerializable()
final class Cart {
  final Map<Id, int> items;
}

@JsonSerializable()
@IdJsonConverter()
final class Id implements Comparable<Id> {
...
}

final class IdJsonConverter extends JsonConverter<Id, String> {
  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:

@pattobrien
Copy link

I would go even further to say that if a particular type has a toJson / fromJson that returns/takes a String type, then the conversion should be implicit (or perhaps put this behind a configuration parameter?).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants