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.
you can use recase package so the code will look like this:
P.S. that package have a lot handy cases