告诉Jackson只在生成xml

时间:2015-10-29 10:01:13

标签: java spring-boot jackson

有没有办法告诉杰克逊只有在生成带注释的XML时才忽略属性?

我有一个通过REST(Spring Boot)公开的JPA实体。我想告诉杰克逊忽视,例如生成XML时的属性street,而不是生成JSON String时的属性street

@Entity
public class anObject{

  String name;

  @JsonIgnore //only when converting to XML? Still need it on a JSON String
  String street

//Various Getters, Setters, etc.
}

提前致谢!

2 个答案:

答案 0 :(得分:2)

我认为你对XML和JSON有不同的ObjectMapper。您只能为XML映射器设置mixin注释。 E.g。

mixin注释:

abstract class anObjectMixIn {
  @JsonIgnore String street;
}

映射器代码:

ObjectMapper jsonMapper = new ObjectMapper();
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.addMixIn(anObject.class, anObjectMixIn.class);

并删除@JsonIgnore超过String street。请注意mixin仅适用于xmlMapper

答案 1 :(得分:0)

Jackson允许您使用JAXB注释,查看JAXB module

你可以同时使用Jackson和JAXB,但你可以告诉the documentation中提到哪一个优先于另一个,所以你可以保留你的核心Jackson注释为JSON,并专注于你的XML序列化的JAXB注释

AnnotationIntrospector primary = new JacksonAnnotationIntrospector();
AnnotationIntrospector secondary = new JaxbAnnotationIntrospector();
AnnotationIntrospector pair = new AnnotationIntrospector.Pair(primaryIntrospector, secondaryIntropsector);
相关问题