简体   繁体   English

忽略杰克逊反序列化的某些字段而无需更改模型

[英]Ignore some fields deserialization with jackson without changing model

I'm looking for a way to configure jackson deserializer to ignore some fields. 我正在寻找一种配置杰克逊解串器以忽略某些字段的方法。 I don't want to achieve this by annotating model since It's out given by another project; 我不想通过注释模型来实现这一点,因为它是由另一个项目给出的。 I just want to do it by constructing deserializer (ObjectMapper) to do so. 我只是想通过构造解串器(ObjectMapper)来做到这一点。
Is it possible? 可能吗?

you have to do following 你必须做以下

1)write your own Deserializer which extends JsonDeserializer 1)编写自己的Deserializer,以扩展JsonDeserializer

2) override deserialize method and return your class object after ignoring some of the fields 2)覆盖反序列化方法并在忽略某些字段后返回您的类对象

3) register your deserializer with ObjectMapper 3)向ObjectMapper注册反序列化器

ObjectMapper mapper = new ObjectMapper();
SimpleModule module = new SimpleModule();
module.addDeserializer(yourClass.class, new yourDerializer());
mapper.registerModule(module);
String newJsonString = "{\"id\":1}";
final yourClass yourClassObject= mapper.readValue(newJsonString, yourClass.class);

Hope this will solve your problem 希望这能解决您的问题

You can achieve that using Mix-In annotation. 您可以使用Mix-In注释来实现。

class ThirdPartyReadOnlyClass {
   private String ignoredPropertyFromThirdParty;

   public String getIgnoredPropertyFromThirdParty() {
      return ignoredPropertyFromThirdParty;
   }
}

abstract class MixIn {
  @JsonIgnore
  String getIgnoredPropertyFromThirdParty();
}

You can put json annotations on MixIn class as if you are putting them on original model class. 您可以将JSON注释放在MixIn类上,就像将它们放在原始模型类上一样。

Configuring object mapper 配置对象映射器

objectMapper.addMixInAnnotations(ThirdPartyReadOnlyClass.class, MixIn.class);

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

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