Search code examples
spring-bootjava-8jackson-dataformat-xml

Ignore xml tags while serializing pojo fields to xml


I am using jackson library to map POJO to XML.

compile ('com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.9.0')

While serializing I need to ignore some of the fields. This is my POJO class. For example, the field lineNumber should be ignored.

@NoArgsConstructor
@AllArgsConstructor
@Getter
@XmlAccessorType(XmlAccessType.FIELD)
public class InvoiceLineItem {

    @JacksonXmlProperty(localName = "LineNumber")
    @XmlTransient
    private Integer lineNumber;

    @JacksonXmlProperty(localName = "ProductCode")
    @XmlTransient
    private String productCode;

    @JacksonXmlProperty(localName = "ProductDescription")
    @XmlTransient
    private String productDescription;
}

I am using @XmlTransient with XmlAccessorType to ignore the fields. But the lineNumber field annotated with XmlTransient is not ignored while serializing.


Solution

  • Try adding the @JsonProperty(access = Access.WRITE_ONLY) annotation to the lineNumber field.

    Even thought it looks like a JSON thing, the Jackson XmlMapper identifies the annotation and reacts accordingly.

    Edit
    The conclusion XmlMapper should support JSON serizlization is an example of the following, incorrect attempt at reasoning:

    1. All men are mortal.
    2. Socrates was mortal.
    3. Therefore, all men are Socrates.

    The XmlMapper is not a wrapper class around ObjectMapper. It came after ObjectMapper and appears to share many features, like the handling of some JSON annotation.