Ruwanka De Silva
Ruwanka De Silva

Reputation: 3755

Serialize XML element having property named value using Jackson

I'm trying to deserialize/serialize xml content with below element.

<?xml version="1.0" encoding="utf-8" ?>
<confirmationConditions>
    <condition type="NM-GD" value="something">no modification of guest details</condition>
</confirmationConditions>

How can I properly create java beans with jackson annotations to parse this correctly. I've tried with JAXB annotations and jackson fails saying it can't be having to value fields. With below java beans I got following error.

public class Condition
{
    @JacksonXmlProperty( isAttribute = true, localName = "type" )
    private String type;
    @JacksonXmlProperty( isAttribute = true, localName = "value" )
    private String value;
    private String text;
}

Error

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "" (class Condition), not marked as ignorable (3 known properties: "value", "type", "text"])
 at [Source: (File); line: 3, column: 73] (through reference chain: ConfirmationConditions["condition"]->Condition[""])

Basically what I want is to map element content to text field. I have no control over xml so changing it would not work for me.

Upvotes: 0

Views: 359

Answers (1)

Naya
Naya

Reputation: 870

The thing you need here is to add @JacksonXmlText

class Condition {
    @JacksonXmlProperty(isAttribute = true)
    private String type;
    @JacksonXmlProperty(isAttribute = true)
    private String value;
    @JacksonXmlText
    private String text;

    public String getType() {
        return type;
    }

    public void setType(String type) {
        this.type = type;
    }

    public String getValue() {
        return value;
    }

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

    public String getText() {
        return text;
    }

    public void setText(String text) {
        this.text = text;
    }
}

And parse it this way:

    JacksonXmlModule module = new JacksonXmlModule();
    module.setDefaultUseWrapper(false);
    XmlMapper xmlMapper = new XmlMapper(module);

    xmlMapper.readValue(
            "<condition type=\"NM-GD\" value=\"something\">no modification of guest details</condition>", Condition.class);

Upvotes: 2

Related Questions