简体   繁体   中英

Tell Jackson to ignore property only when generating an xml

Is there a way to tell Jackson to only ignore a property if it generates XML with annotations?

I have a JPA entity which is exposed via REST (Spring Boot). I'd like to tell Jackson to ignore eg the property street when generating XML but not when generating a JSON String

@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.
}

Thanks in advance!

I presume you have different ObjectMapper for XML and JSON. You can set a mixin annotation only for the XML mapper. Eg

the mixin annotation :

abstract class anObjectMixIn {
  @JsonIgnore String street;
}

the mapper code :

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

And delete the @JsonIgnore over String street . Note how the mixin is only applied on xmlMapper

Jackson allows you tu use JAXB annotations, have a look at the JAXB module .

You can use both Jackson and JAXB together but you can tell which one has priority over the other as mentioned in the documentation , so you can keep your core Jackson annotations for JSON and specialize with JAXB annotations for your XML serialisation.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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