Created
June 8, 2023 13:04
-
-
Save keksipurkki/ec2602ba8849697fbb9a3ecfd4102ec7 to your computer and use it in GitHub Desktop.
NullableEnumConverter.java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class NullableEnumConverter implements ModelConverter { | |
@Override | |
public Schema<?> resolve(AnnotatedType type, ModelConverterContext context, Iterator<ModelConverter> chain) { | |
var schema = chain.next().resolve(type, context, chain); | |
if (isNull(schema)) { | |
return schema; | |
} | |
var javaType = Json.mapper().constructType(type.getType()); | |
if (!javaType.isEnumType()) { | |
return schema; | |
} | |
var annotation = findAnnotation(type, javaType); | |
if (nonNull(annotation) && schema instanceof StringSchema) { | |
var stringSchema = (StringSchema) schema; | |
stringSchema.addEnumItem(null); | |
} | |
return schema; | |
} | |
Annotation findAnnotation(AnnotatedType type, JavaType javaType) { | |
var annotation = javaType.getRawClass().getAnnotation(NullableEnum.class); | |
if (annotation != null) { | |
return annotation; | |
} | |
for (var contextAnnotation : type.getCtxAnnotations()) { | |
if (contextAnnotation.annotationType().equals(NullableEnum.class)) { | |
return contextAnnotation; | |
} | |
} | |
return null; | |
} | |
@Retention(RetentionPolicy.RUNTIME) | |
public @interface NullableEnum { | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment