如何将自定义类加载器添加到ObjectMapper?

问题描述 投票:1回答:3

有没有办法指示Jackson 2 ObjectMapper使用自定义类加载器来反序列化JSON字符串?

json classloader jackson
3个回答
1
投票

这是解决方案:

ClassLoader myClassLoader = ...        

ObjectMapper om = new ObjectMapper();
TypeFactory tf = TypeFactory.defaultInstance()
                            .withClassLoader(myClassLoader);
om.setTypeFactory(tf);

0
投票

查看Jackson Wiki for Modules,Jackson Module可用于创建自定义序列化/反序列化。虽然wiki谈论他们可以做什么

添加自定义序列化程序和反序列化程序

添加混合注释

覆盖或添加AnnotationIntrospector

访问SerializationConfig和DeserializationConfig设置。

它非常清楚细节,只是给出了一个非常基本的例子。 Module JavaDoc也很注重细节。幸运的是,wiki在GitHub上也有一个list of existing Jackson Modules,如果您需要从头开始创建自己的模块,这将更有用。


0
投票

要保留现有的TypeMapper,您可能希望执行类似的操作(这是Scala,但相同的模式适用于Java),您可以在其中调整当前类型的工厂。

  def updateClassLoader(cl: ClassLoader): Unit = {
    objectMapper.setTypeFactory(objectMapper.getTypeFactory.withClassLoader(cl))
  }

这将保留来自可能的先前配置调用的缓存类型数据,如下所示:

mapper.registerModule(new Jdk8Module)
      .registerModule(new JavaTimeModule)
      .registerModule(new DefaultScalaModule)
© www.soinside.com 2019 - 2024. All rights reserved.