-
Notifications
You must be signed in to change notification settings - Fork 9
enum mapping in lowercase fails by default #198
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
Comments
say the same shortly :
is not the same as
|
yes, this is annoying. the question is how to improve it.
any other idea? |
Second point is far more annoying, because each enum must have its converter registered. Having a special interface on the enum i.e like "Supplier<String>" would allow :
with :
and
This is only suggestions. |
I have successfully created a prototype import org.springframework.core.convert.converter.Converter;
import org.springframework.core.convert.converter.ConverterFactory;
import org.springframework.stereotype.Component;
import java.util.EnumSet;
import java.util.function.Supplier;
public class StringToEnumConverterFactory<T extends Enum<T> & Supplier<String>> implements ConverterFactory<String, T> {
@Override
@SuppressWarnings({"unchecked", "rawtypes"})
public <E extends T> Converter<String, E> getConverter(Class<E> targetType) {
return new StringToEnumConverter(targetType);
}
static class StringToEnumConverter<T extends Enum<T> & Supplier<String>> implements Converter<String, T> {
private final Class<T> enumType;
public StringToEnumConverter(Class<T> enumType) {
this.enumType = enumType;
}
public T convert(String source) {
String sourceValue = source.trim();
for (T e : EnumSet.allOf(enumType)) {
if (e.get().equals(sourceValue)) {
return e;
}
}
throw new IllegalArgumentException(
String.format("No enum constant of %s has the value %s", enumType.getCanonicalName(), sourceValue));
}
}
} It requires a one time registration using Your Thanks for your input :-) |
…straints annotation
…rated test file filter
…e additional packages
…e additional packages
improved in 2023.6, added |
I have a legacy API that takes an enumeration as argument, here is a yaml fragment of OpenAPI spec :
Such enumeration should be used as string in API, but is translated to Enum with processor (why not, this is not the problem) as :
Internally spring use StringToEnumConverterFactory to convert the string to enumeration:
and it fail, because Enum.valueOf(Mode.class, "a") delegates to internal enumConstantDirectory which contains only uppercase values "A" and "B" !
So the only workaround is to inject custom converter, but this is not desirable.
The text was updated successfully, but these errors were encountered: