繁体   English   中英

如何将依赖注入 Jackson 自定义序列化程序

[英]How to inject dependency into Jackson Custom serializer

这个问题中,我看到了一种有趣的方法,用于将对象注入 Jackson 映射框架的自定义反序列化器(我目前使用的是2.10.x 版)。 本质上,在ObjectMapper注册一个依赖项 MyService

 jsonMapper.setInjectableValues(new InjectableValues
                .Std()
                .addValue(MyService.class.getName(), myServiceInstance));

然后在扩展StdDeserializer的类中,可以通过具有findInjectableValue方法的DeserializationContext访问它。

现在,我希望图书馆提供一种对称的序列化方法,但老实说找不到它。 具体来说,如果您有一个扩展StdSerializer的类,您将需要实现一个方法serialize(ProjectSerializable value, JsonGenerator jsonGenerator, SerializerProvider provider) ,该方法似乎没有具有与DeserializationContext类似功能的类。

那么,如何使用自定义序列化程序实现相同的“注入”,而无需求助于基于对实例提供程序或其他不可测试事物的静态访问的丑陋解决方案。

在我看来,实现这一点的唯一方法是为自定义序列SerializerProvider程序将使用的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的实例。

我不喜欢与反序列化显示的其他方法的不对称性,但它有效。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM