Looks like there is another approach (Thanks to one of my colleague) using injectableValues on the objectMapper instance and then fetch the dependency through DeserializationContext ctxt. Following is the code.
ObjectMapper guice module.
public class MerchantConverterModule extends AbstractModule {
@Override
protected void configure() {
}
@Provides
@Singleton
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
/**
* Add dependency object to object mapper.
*/
objectMapper.setInjectableValues(new InjectableValues
.Std()
.addValue("DependencyName", dependency));
return objectMapper;
}
}
Code of your custom deserializer
public class CustomDeserializer extends StdDeserializer<String> {
private SomeDependecy dependency;
public StringDeserializer() {
this(null);
}
@Override
public String deserialize(JsonParser p, DeserializationContext ctxt) throws IOException, JsonProcessingException {
return getDependency(ctxt).perform(p.getValueAsString());
}
private SomeDependency getDependency(DeserializationContext ctxt) {
SomeDependency dependency = (SomeDependency) ctxt
.findInjectableValue("DependencyName", null, null);
return dependency;
}
}
findInjectableValue
method is a final method, so you might need to tweak your unit test code to mock finals.
NOTE: The drawback is that there is a tight coupling between the objectmapper and deserializer.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…