Jersey在序列化期间省略了XmlTransient注释

时间:2017-02-11 16:02:07

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

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

{
    "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一起使用。

1 个答案:

答案 0 :(得分:2)

在Jackson 2.x中,可以使用适当的AnnotationIntrospector来实现。

支持Jackson和JAXB注释

要同时支持Jackson和JAXB注释,您需要JacksonAnnotationIntrospectorJaxbAnnotationIntrospector。两个内省检者都可以与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