I have a class that extends JsonDerserializer<Type>
. In this deserialiser I have a concept of doing replacement values which I currently set using objectReader(Injectables). My problem is that sometimes I don't have injectables.
I don't see a method on ObjectMapper
that allows me to check if an injectable key is set. I only see findInjectableValue
which if the value isn't there it throws an InvalidDefinitionException
. I am currently try catching this call which works, but I feel it is more of a hack.
Is there something I am missing?
I really don't want to have this try-catch
. I want to first check if injectable value exists.
try {
Object replacementValueObject = ctxt.findInjectableValue("replacementValues", null, null);
if (replacementValueObject instanceof Map) {
replacementValues = (Map<String, Object>) replacementValueObject;
mapper.setInjectableValues(new InjectableValues.Std().addValue("replacementValues", replacementValues));
}
}catch (InvalidDefinitionException ie){
logger.info("No replacement values exist. Ignoring and moving on");
}
Right now (07-2019
), there is no method to check whether value exists or not. You can only addValue and try to get it by invoking findInjectableValue.
You can create empty Map
and initialise InjectableValues
when ObjectMapper
is created:
InjectableValues.Std injectableValues = new InjectableValues.Std();
injectableValues.addValue("replacementValues", Collections.emptyMap());
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setInjectableValues(injectableValues);
or create nice method which hides complex logic behind scene:
class ReplaceMapValueJsonDeserializer extends JsonDeserializer<Object> {
@Override
public Object deserialize(JsonParser p, DeserializationContext ctxt) {
return null;
}
@Override
public Object deserialize(JsonParser p, DeserializationContext ctxt, Object intoValue) throws IOException {
Map replacementValues = getCurrentReplacementValues(ctxt);
//...
return super.deserialize(p, ctxt, intoValue);
}
private Map<String, Object> getCurrentReplacementValues(DeserializationContext ctxt) {
try {
Object value = ctxt.findInjectableValue("replacementValues", null, null);
return (Map<String, Object>) value;
} catch (JsonMappingException ie) {
return Collections.emptyMap();
}
}
}
See also: