在 this我看到了一种有趣的方法,用于将对象注入(inject) Jackson 映射框架的自定义反序列化器中(我目前使用的是版本 2.10.x)。
本质上,我们在 ObjectMapper
jsonMapper.setInjectableValues(new InjectableValues
.Std()
.addValue(MyService.class.getName(), myServiceInstance));
然后在扩展 StdDeserializer
的类中,可以通过具有 findInjectableValue
方法的 DeserializationContext
访问它。
现在,我希望该库提供一种对称的序列化方法,但老实说找不到它。具体来说,如果您有一个扩展 StdSerializer 的类,则需要实现一个方法 serialize(ProjectSerializing value, JsonGenerator jsonGenerator, SerializerProviderprovider)
,该方法似乎没有具有与 DeserializationContext
类似功能的类。
那么,如何使用自定义序列化器实现相同的“注入(inject)”,而不诉诸基于对实例提供程序或其他不可测试事物的静态访问的丑陋解决方案。
最佳答案
在我看来,实现此目的的唯一方法是通过设置自定义序列化程序将使用的 SerializerProvider
属性。
当您创建ObjectMapper
时,您必须通过创建一个新的来破解它
ObjectMapper objectMapper = ...// here you create the ObjectMapper will all your configs
// Then you inject the service.
SerializationConfig initialSerializationConfig = objectMapper.getSerializationConfig();
ContextAttributes attributes = initialSerializationConfig.getAttributes();
// Here we create a new ContextAttributes with the class we want
// to have shared for each serializer
ContextAttributes attributesWithInjectedValue =
attributes.withSharedAttribute(MyService.class.getName(), myServiceInstance);
SerializationConfig serializationConfigWithInjectedValue =
initialSerializationConfig.with(attributesWithInjectedValue);
return jsonMapper.setConfig(serializationConfigWithInjectedValue);
然后在 JsonSerializer
的实例中,您只需执行以下操作:
MyService myService = (MyService) serializerProvider
.getAttribute(MyService.class.getName());
其中 serializerProvider
是使用 serialize
方法给出的 SerializerProvider
实例。
我不喜欢与其他反序列化方法的不对称性,但它确实有效。
关于java - 如何将依赖项注入(inject) Jackson 自定义序列化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60239238/