简体   繁体   English

Jackson在一个POJO中反序列化了两种不同的Json表示形式

[英]Jackson deserialize two different Json representations in one POJO

Is it possible to deserialize two different representations in the same pojo object, for example when optional translations can be returned. 是否可以在同一pojo对象中反序列化两个不同的表示形式,例如,当可以返回可选翻译时。

For example, this is my pojo: 例如,这是我的pojo:

class LightCustomer {
  enum TITLE {
    Mr, Mrs, Ms
  }
  public TITLE title;
  public String titleLabel;
}

No problem with first available representation : 第一个可用表示形式没有问题:

{
  "title": "Mrs"
}

My second representation with translation : 我的第二个翻译代表:

{
  "title": {
    "value": "Mrs",
    "label": "Madame"
  }
}

There is an way to : 有一种方法可以:

  • deserialize "title" or "title.value" in LightCustomer.setTitle() ? 在LightCustomer.setTitle()中反序列化“ title”或“ title.value”?
  • deserialize "title.label" in LightCustomer.setTitleLabel() ? 在LightCustomer.setTitleLabel()中反序列化“ title.label”?

You can use @JacksonRootName for the second representation. 您可以使用@JacksonRootName作为第二个表示形式。

@JsonRootName(value = "title")
class LightCustomer {
  enum TITLE {
    Mr, Mrs, Ms
  }
  public TITLE title;
  public String label;
}

Configure the ObjectMapper instance with 使用以下命令配置ObjectMapper实例

mapper.configure(Feature.UNWRAP_ROOT_VALUE, true); //version 1.9

or 要么

mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true); //version 2

You can use different ObjectMapper instance for example. 例如,您可以使用其他ObjectMapper实例。 I'm not entirely sure if it is a good idea though. 我不完全确定这是否是个好主意。 Perhaps a better way: create custom serializer/deserializer that allow both representation to be handled by a single instance of ObjectMapper. 也许是一种更好的方法:创建自定义的序列化器/反序列化器,以允许通过ObjectMapper的单个实例来处理两种表示形式。

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

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