【问题标题】:Jersey omits XmlTransient annotation during serializationJersey 在序列化期间省略了 XmlTransient 注释
【发布时间】:2017-02-11 16:02:07
【问题描述】:

有一个要求将java.util.Date 格式化为字符串而不是 json 中的时间戳。

{
    "partyName": "Lifecare Pharmaceuticals",
    "partyShortName": null,
    "lastUpdateDate": 1486639814590, // replace with dd-mm-yyyy hh:mm:ss
}

为了实现日期格式,我添加了以下 ObjectMapperProvider

@Provider
@Component
public class ObjectMapperProvider implements ContextResolver<ObjectMapper> {

   @Override
   public ObjectMapper getContext(Class<?> type) {
      ObjectMapper objectMapper = new ObjectMapper();
      objectMapper.enable(SerializationConfig.Feature.USE_ANNOTATIONS);
      objectMapper.configure(SerializationConfig.Feature.WRITE_DATES_AS_TIMESTAMPS, false);
      return objectMapper;
    }
}

上述解决方案有效,但会产生另一个忽略 XmlTransient 注释的问题。在模型类中,Party 集合了 PartyContactsPartyContact 映射

@Column(name = "PARTY_ID", referencedColumnName = "PARTY_ID", insertable = false, updatable = false)
@ManyToOne(cascade = CascadeType.ALL, optional = false, fetch =FetchType.LAZY)
private Party party;

和getter方法

@XmlTransient
public Party getParty() {
    return party;
}

这里 XmlTransient 注释不起作用,因此 json 递归加载。我又看到了一个 @JsonIgnore 注释,但无法使其与 XmlTransient 一起使用。

【问题讨论】:

    标签: java json jackson jax-rs jersey-1.0


    【解决方案1】:

    在 Jackson 2.x 中,它可以通过适当的 AnnotationIntrospector 来实现。

    同时支持 Jackson 和 JAXB 注释

    要同时支持 Jackson 和 JAXB 注释,您需要一个 JacksonAnnotationIntrospector 和一个 JaxbAnnotationIntrospector。两个内省都可以与AnnotationIntrospectorPair 结合使用:

    AnnotationIntrospector primary = new JacksonAnnotationIntrospector();
    AnnotationIntrospector secondary = new JaxbAnnotationIntrospector();
    AnnotationIntrospector pair = new AnnotationIntrospectorPair(primary, secondary);
    mapper.setAnnotationIntrospector(pair);
    

    仅支持 JAXB 注释

    如果您只想支持 JAXB 注解,请仅注册 JaxbAnnotationIntrospector:

    AnnotationIntrospector introspector = new JaxbAnnotationIntrospector();
    mapper.setAnnotationIntrospector(introspector);
    

    依赖

    要使用JaxbAnnotationIntrospector,需要以下依赖:

    <dependency>
        <groupId>com.fasterxml.jackson.module</groupId>
        <artifactId>jackson-module-jaxb-annotations</artifactId>
        <version>2.8.6</version>
    </dependency>
    

    更多详情,请查看jackson-module-jaxb-annotations module documentation

    【讨论】:

    • 完美,有效。我还有一个问题,除了提供new ObectMapper 之外,我们不能访问 Jersey 使用默认值的现有 objectMapper 并附加额外的配置吗?
    • @vels4j 不存在现有的ObjectMapper。序列化和反序列化由其他 Jackson API 处理。
    猜你喜欢
    • 2012-06-09
    • 2014-08-31
    • 1970-01-01
    • 2011-11-23
    • 2019-05-14
    • 2020-12-15
    • 2018-06-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多