简体   繁体   English

是否可以忽略@JsonSerialize注释?

[英]Is it possible to ignore @JsonSerialize annotation?

Is it possible to serialize object using Jackson,but ignoring custom serializers registered with annotation @JsonSerialize(using = MyCustomSerializer.class) ? 是否可以使用Jackson序列化对象,但忽略使用注释@JsonSerialize(using = MyCustomSerializer.class)注册的自定义序列化@JsonSerialize(using = MyCustomSerializer.class)

Rationale: I want to use Jackson to convert my object to Map, using com.fasterxml.jackson.databind.ObjectMapper.convertValue(object,Map.class) . 基本原理:我想使用Jackson将我的对象转换为Map,使用com.fasterxml.jackson.databind.ObjectMapper.convertValue(object,Map.class) Currently it does not work, because my class has custom serializer (@JsonSerialize) but misses deserializer. 目前它不起作用,因为我的类有自定义序列化程序(@JsonSerialize)但错过了反序列化程序。 I require custom serializer, and I really do not need and do not want to write deserializer. 我需要自定义序列化器,我真的不需要也不想编写反序列化器。

ObjectMapper.convertValue uses my serialization then fails at deserialization. ObjectMapper.convertValue使用我的序列化然后在反序列化时失败。

I would like to have ObjectMapper that will just ignore @JsonSerialize and use default serialization logic. 我想让ObjectMapper忽略@JsonSerialize并使用默认的序列化逻辑。 Is that possible with Jackson? 杰克逊有可能吗?

That is entirely possible. 这完全有可能。 You could disable annotations on a per ObjectMapper basis, like this: 您可以在每个ObjectMapper的基础上禁用注释,如下所示:

ObjectMapper mapper = new ObjectMapper();
mapper.disable(MapperFeature.USE_ANNOTATIONS);

For more details check the documentation over at github or check the examples at baeldung . 有关更多详细信息,请查看github上的文档或查看baeldung上的示例。

you could also disable a spesific annoation by using ignoreJsonTypeInfoIntrospector and return null for the spsific annoation class; 您还可以通过使用ignoreJsonTypeInfoIntrospector禁用特定的annoation,并为spsific annoation类返回null;

take a look at the last github issue 看看最后一个github问题

public class IgnoreJsonUnwrappedAnnotationInspector extends JacksonAnnotationIntrospector {
  @Override
  public NameTransformer findUnwrappingNameTransformer(AnnotatedMember member) {
    return null;
  }
}

also take a look here for more detailed example 另请看这里更详细的例子

another solution is to create more ObjectMapper instances for the different scenarios. 另一种解决方案是为不同的场景创建更多的ObjectMapper实例。

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

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