I was searching a way to serialize & deserialize my enum with different cases (camelCase to snake_case) and I discovered the @JsonEnum
parameter offered by the Json_serializable package.
That's exactly what I needed! It works perfectly for de-serialization (String to JSON) and should (not tested) for serialization too.
However I would like to know if there is a getter
or function that allows to get the "string" representation of an enum value that takes in account the fieldRename
parameter.
My use case concern a GET request where I will not convert my enum to JSON but only use its string value to pass it as ?param=<enum_value_str>
Example of what I am looking for
@JsonEnum(fieldRename: FieldRename.snake)
enum A {
firstValue,
secondValue,
thirdValue,
}
print(A.name) // -> firstValue
print(A.toJson()) // This does not exist, the expected output -> first_value
If anybody has any idea on how to solve this it wuold be great!
As a workaround, I defined an extension that contains a method called str
extension AExtension on A {
String get str {
switch (this) {
case A.firstValue:
return 'first_value';
case A.secondValue:
return 'second_value';
case A.thirdValue:
return 'third_value';
}
}
}
That works but I think the fieldRename
parameter would work way better if I can find a function to retrieve the "JSON string representation" of the enum value.
a.dart file
import 'package:json_annotation/json_annotation.dart';
part 'a.g.dart';
@JsonEnum(
fieldRename: FieldRename.snake,
alwaysCreate: true,
)
enum A {
firstValue,
secondValue,
thirdValue;
String toJson() => _$AEnumMap[this]!;
factory A.fromJson(String json) =>
_$AEnumMap.map((key, value) => MapEntry(value, key))[json]!;
}
a.g.dart
// GENERATED CODE - DO NOT MODIFY BY HAND
part of 'a.dart';
// **************************************************************************
// JsonSerializableGenerator
// **************************************************************************
const _$AEnumMap = {
A.firstValue: 'first_value',
A.secondValue: 'second_value',
A.thirdValue: 'third_value',
};
Add alwaysCreate: true
to JsonEnum
annotation will create a toJson map for the enum even if it's not used in another place
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With