在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
中,PartyContacts
和PartyContact
的集合映射为
@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一起使用。
答案 0 :(得分:2)
在Jackson 2.x中,可以使用适当的AnnotationIntrospector
来实现。
要同时支持Jackson和JAXB注释,您需要JacksonAnnotationIntrospector
和JaxbAnnotationIntrospector
。两个内省检者都可以与AnnotationIntrospectorPair
:
AnnotationIntrospector primary = new JacksonAnnotationIntrospector();
AnnotationIntrospector secondary = new JaxbAnnotationIntrospector();
AnnotationIntrospector pair = new AnnotationIntrospectorPair(primary, secondary);
mapper.setAnnotationIntrospector(pair);
如果您只想支持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。