google / json_serializable.dart

Generates utilities to aid in serializing to/from JSON.
https://pub.dev/packages/json_serializable
BSD 3-Clause "New" or "Revised" License
1.54k stars 393 forks source link

Allow more than one value map to the same enum value with `@JsonValue` #1380

Open mateusfccp opened 7 months ago

mateusfccp commented 7 months ago

Currently, we can use @JsonValue in an enum to define what value maps to it.

enum CustomType {
  @JsonValue('a')
  valueA,
  @JsonValue('b')
  valueB,
  @JsonValue('c')
  valueC,
}

Now, I want to map more than one value to the same enum value. I cannot do this unless I write a custom JsonConverter for the enum.

This issue proposes that we have a way to tell json_serializable that we want more than one value to be mapped to our enum value.

For instance:

enum CustomType {
  @JsonValue('valueA')
  @JsonValue('a')
  valueA,
  @JsonValue('valueB')
  @JsonValue('b')
  valueB,
  @JsonValue('valueC')
  @JsonValue('c')
  valueC,
}
Xazin commented 7 months ago

I would assume a new decorator eg. @MultiJsonValues(['valueA', 'a']) to be more proper, or an argument on the existing decorator like so @JsonValue('a', aliases: ['valueA', 'A']).

I wouldn't know if this is possible since I have not looked deeply at the code.

mateusfccp commented 6 months ago

Maybe the aliases approach would be better, as we should have a "canonical" reference to use in toJson. While fromJson could map from many different values to a single value, when converting this value to JSON, we can only have a single option, which would be the non-alias one.