Equivalent to @JsonIgnore, but which only works for converting the xml / property field using Jackson

I have a class that I serialize / deserialize from / to JSON, XML using Jackson.

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

I want to ignore groupId when processing xml, so my XML will not include it:

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

But JSONs will be:

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

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

I know about mixing annotations that can be used to do this ( https://stackoverflow.com/a/164778/ ), but I think there should be a simple annotation that does this, but cannot find it. Jackson's documentation (at least for me) is not as good as I would have liked when trying to find such things.

+4
1

. "Jackson json views" , XML- @JsonIgnore .

:

public class JacksonXmlAnnotation {
    @Retention(RetentionPolicy.RUNTIME)
    public static @interface JsonOnly {
    }

    @JacksonXmlRootElement(localName = "root")
    public static class User {
        public final Integer userId;
        public final String name;
        @JsonOnly
        public final Integer groupId;

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

    public static class XmlAnnotationIntrospector extends JacksonXmlAnnotationIntrospector {
        @Override
        public boolean hasIgnoreMarker(AnnotatedMember m) {
            return m.hasAnnotation(JsonOnly.class) || super.hasIgnoreMarker(m);
        }
    }

    public static void main(String[] args) throws JsonProcessingException {
        User user = new User(1, "John", 23);
        XmlMapper xmlMapper = new XmlMapper();
        xmlMapper.setAnnotationIntrospector(new XmlAnnotationIntrospector());
        ObjectMapper jsonMapper = new ObjectMapper();
        System.out.println(xmlMapper.writerWithDefaultPrettyPrinter().writeValueAsString(user));
        System.out.println(jsonMapper.writerWithDefaultPrettyPrinter().writeValueAsString(user));
    }
}

:

<root>
  <userId>1</userId>
  <name>John</name>
</root>
{
  "userId" : 1,
  "name" : "John",
  "groupId" : 23
}
+6

Source: https://habr.com/ru/post/1545874/


All Articles