'Equivalent of @JsonIgnore but that works only for xml field/property conversion using Jackson

I have a class that I am serializing/deserializing from/to both JSON, XML using Jackson.

public class User {
    Integer userId;
    String name;
    Integer groupId;
...
}

I want to ignore groupId when doing xml processing, so my XMLs won't include it:

<User>
 <userId>...</userId>
 <name>...</name>
</User>

But the JSONs will:

{
  "userId":"...",
  "name":"...",
  "groupId":"..."
}

I know that @JsonIgnore will work in both, but I want to ignore it only in the xml.

I know about the mix-in annotations that can be used to do this (https://stackoverflow.com/a/22906823/2487263), but I think there should be a simple annotation that does this, but cannot find it. Jackson documentation (at least for me) is not as good as I would like when trying to find these kind of things.



Solution 1:[1]

You can use JacksonAnnotationIntrospector with @JsonIgnore(false)

User class:

    public static class User {
      public final Integer userId;
      public final String name;
      @XmlTransient
      @JsonIgnore(false)
      public final Integer groupId;

      public User(Integer userId, String name, Integer groupId) {
        this.userId = userId;
        this.name = name;
        this.groupId = groupId;
      }
    }

Set annotation introspector to ObjectMapper

ObjectMapper jsonMapper = new ObjectMapper();
jsonMapper.setAnnotationIntrospector(new JacksonAnnotationIntrospector());

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aleksandr