json_serializable.dart
json_serializable.dart copied to clipboard
[Feature Request] Enum value with enhanced Enums
Feature request related to Enhanced enums while using JsonValue
- Currently, we would have to declare the value twice per Enum value (to allow this package to serialize/deserialize the Enum and to have access to
.value
)
import 'package:json_annotation/json_annotation.dart';
part 'status_code.g.dart';
enum StatusCode {
@JsonValue(200)
success(200),
@JsonValue(500)
weird(500),
const StatusCode(this.value);
final int value;
}
It would be much better if we could have the generated map EnumMap
to use the value specified in the constructor
I have no idea how could generation work in the package, but one possibility will be offer some kind of interface EnumValue<T>
to be implemented by the Enum, thus making the T value
required to be implemented. Then a check for Enums implementing this interface and use the value passed in the constructor to create the EnumMap
with the code generation.
Or we could "steal" the JasonValue
annotation and put it on the enum
definition with the field name – in the case above "value"
.
The package is not setup to support adding language-specific features until we're ready to bump the min SDK, so it'll likely be a while until we get there.
https://github.com/google/json_serializable.dart/pull/1180 bumps the min version of the required SDK – we could entertain this now!
Hey, did this get any updates? I am running the latest version and it's still generating by name. Am I missing something?
Looking now!
This feature has been added as of
https://pub.dev/packages/json_annotation/versions/4.7.0 and https://pub.dev/packages/json_serializable/versions/6.4.0
@kevmoo Sorry for coming back on this. Just to make things clear, when using the new syntax of enhanced enums should we still use the @JsonValue annotation on top of each enum value or does the library takes care of it?
Looks that json_convert always generates a string representation of the enum name when there is no @JsonValue and not the declared enum values.
Just use @JsonEnum
on the enum itself. @JsonValue
should no longer be needed.
@kevmoo Perfect! Thank you