Jackson的动态多态类型处理 [英] Dynamic polymorphic type handling with Jackson

查看:743
本文介绍了Jackson的动态多态类型处理的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似于这个的类层次结构:

I have a class hierarchy similar to this one:

public static class BaseConfiguration {
}

public abstract class Base {
  private BaseConfiguration configuration;
  public String id;

  public BaseConfiguration getConfiguration() { ... }
  public void setConfiguration(BaseConfiguration configuration) { ... }
}

public class A extends Base {
   public static class CustomConfigurationA extends BaseConfiguration {
       String filename;
       String encoding;
   }

   CustomConfigurationA getConfiguration() { ... }
}

class B extends Base {
   public static class CustomConfigurationB extends BaseConfiguration {
       /* ... */
   }

   CustomConfigurationB getConfiguration() { ... }
}

和json一样输入(我自己无法改变)

And json input like this one (which I cannot change myself)

{
    "id":"File1",
    "configuration":{
         "filename":"...",
         "encoding":"UTF-8"
     }
}

我在Java中解析JSON和Jackson一样

I am parsing the JSON in Java with Jackson like this

ObjectMapper mapper = new ObjectMapper();
value = mapper.readValue(in, nodeType);

我想使用JAVA / Jackson从JSON反序列化A,B等类。 JSON中没有嵌入类型信息(也不可能)。我不能在类上使用注释(我不拥有它们)而且我(相信)我不能使用mixin,因为可能有任意数量的类,比如A& B(和mixins不是动态的)。好的是,反序列化代码知道哪个是用于反序列化的正确自定义类(基本上有从类到配置类的已知映射),但我不知道如何使杰克逊在反序列化JSON时识别此信息。

I want to deserialize classes A, B and others from JSON using JAVA/Jackson. There are no type information embedded in JSON (and can't be). I can't use annotations on the classes (I don't own them) and I (believe) I can't use mixins since there are potentially arbitrary numbers of classes like A & B (and mixins are not dynamic). Good thing is that the deserializing code knows which is the correct custom class to use for deserializing (basically there is a known mapping from class to configuration class), but I do not know how make Jackson recognize this information when deserializing the JSON.

简而言之:我希望能够通过设置ObjectMapper上的必要内容,根据周围的类类型解析配置对象的反序列化类型。如何实现?

In short: I want to be able to resolve the deserialization type of the configuration object depending on the surrounding class type by setting whatever is necessary on ObjectMapper. How can this be achieved?

推荐答案

显然答案是实现类似于 http://programmerbruce.blogspot.com/2011/05/deserialize-json- with-jackson-into.html ,它使用唯一的JSON元素名称来标识要反序列化的目标类型。

Apparently the answer was to implement something similar to the sixth solution posted at http://programmerbruce.blogspot.com/2011/05/deserialize-json-with-jackson-into.html, which uses unique JSON element names to identify the target type to deserialize to.

这篇关于Jackson的动态多态类型处理的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆