简体   繁体   中英

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.

For example, this is my 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() ?
  • deserialize "title.label" in LightCustomer.setTitleLabel() ?

You can use @JacksonRootName for the second representation.

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

Configure the ObjectMapper instance with

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. 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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