Search code examples
javaxmljacksonfasterxmlxml-attribute

fasterxml serialization of an attribute


I'm using fasterxml 2.9.4 per the below and trying to serialise the CurrencyAndAmount class inside a parent class as:

<ParentClass Currency="USD">100000</ParentClass>

But instead I am getting below. The documentation suggests that isAttribute is what I need by is not working for me. What am I missing? Thank you in advance for any pointers in the correct direction.

<ParentClass>100000</ParentClass>

Dependencies:

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.4</version>
 </dependency>
 <dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.9.9</version>
 </dependency>

XmlMapper configuration:

mapper.configure(MapperFeature.ACCEPT_CASE_INSENSITIVE_PROPERTIES, true);
mapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
AnnotationIntrospector primary = new JacksonAnnotationIntrospector();
AnnotationIntrospector secondary = new JaxbAnnotationIntrospector(TypeFactory.defaultInstance());
mapper.setAnnotationIntrospector(AnnotationIntrospector.pair(primary, secondary));

POJO:

public class CurrencyAndAmount {
    @JacksonXmlText
    protected BigDecimal value;
    @JacksonXmlProperty(localName = "Currency", isAttribute = true)
    protected String currency;

    @JsonValue
    public BigDecimal getValue() {
        return value;
    }

    public void setValue(BigDecimal value) {
        this.value = value;
    }

    public String getCurrency() {
        return currency;
    }

    public void setCurrency(String value) {
        this.currency = value;
    }
}

Solution

  • You should remove JsonValue annotation and simplify your POJO to:

    class CurrencyAndAmount {
    
        @JacksonXmlText
        protected BigDecimal value;
    
        @JacksonXmlProperty(localName = "Currency", isAttribute = true)
        protected String currency;
    
        ...
    }