I am working on a web project, that uses one static ObjectMapper, which is configured through an XML file and is supposed to take effect across the whole project. However, I have to implement an API to send a response with the null property not being ignored no matter the setting. My boss told me that he doesn't want another ObjectMapper being created, and creating my own JSON writer is considered redundant so it is forbidden as well. Which caused me stuck here. I tried this.
Map<String, Object>resultMap = getResult();
try {
mapper.setSerializationInclusion(Include.ALWAYS);
response = mapper.writeValueAsString(resultMap);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
} finally {
if (ServiceConfig.isWriteNull()) {
mapper.setSerializationInclusion(Include.ALWAYS);
} else {
mapper.setSerializationInclusion(Include.NON_NULL);
}
}
To temporally switch the settings, it works. but considering the mapper being used asynchronously, it is definitely a bad idea to change the global configuration. I also thought about putting a lock on the mapper until the configuration switchback, but since the mapper is static, it may be another bad idea. I would like to have some neat way like annotation or a parameter magically affect an single execution. I wonder if it is possible?