Created
August 9, 2019 09:02
-
-
Save vandeseer/c21c7b8ca7060f7697d5b64a9b66d908 to your computer and use it in GitHub Desktop.
A custom Jackson serializer for "additionalProperties" (OpenAPI)
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 AdditionalPropertiesSerializer extends StdSerializer<HashMap<String, Object>> { | |
private static final Logger LOGGER = getLogger(); | |
public AdditionalPropertiesSerializer(Class<HashMap<String, Object>> clazz) { | |
super(clazz); | |
} | |
@Override | |
public void serialize(HashMap<String, Object> classExtendedFromHashMap, JsonGenerator jsonGenerator, SerializerProvider provider) throws IOException { | |
jsonGenerator.writeStartObject(); | |
// First handle the fields of the class | |
for (Field field : classExtendedFromHashMap.getClass().getDeclaredFields()) { | |
if (field.isAnnotationPresent(JsonProperty.class)) { | |
try { | |
field.setAccessible(true); | |
JsonProperty jsonProperty = field.getAnnotation(JsonProperty.class); | |
jsonGenerator.writeObjectField(jsonProperty.value(), field.get(classExtendedFromHashMap)); | |
} catch (IllegalAccessException exception) { | |
LOGGER.error("Could not serialize a class that extends HashMap", exception); | |
} | |
} | |
} | |
// Then handle the map's entries | |
for (Map.Entry<String, Object> entry : classExtendedFromHashMap.entrySet()) { | |
jsonGenerator.writeFieldName(entry.getKey()); | |
jsonGenerator.writeObject(entry.getValue()); | |
} | |
jsonGenerator.writeEndObject(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment