taygetos
taygetos

Reputation: 3040

Jackson FasterXML transforming to POJO with namespaces

I want to use FasterXML to

  1. transform an xml into a java object,
  2. transform it back to an xml
  3. and produce the exact same output with namespaces

Here is the original XML:

<customer xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://example.com">
    <dataList>
        <data xsi:type="keyValuePair">
            <key>key1</key>
            <value>val1</value>
        </data>
        <data xsi:type="keyValuePair">
            <key>key2</key>
            <value>val2</value>
        </data>
    </dataList>
    <id>123</id>
</customer>

I am using the following POJOs:

@JacksonXmlRootElement(namespace = "http://example.com")
public class Customer {

  @JacksonXmlProperty
  private String id;
  @JacksonXmlProperty
  @JacksonXmlElementWrapper(localName = "dataList")
  private List<KeyValueData> data;

  public Customer(){}

  public String getId() {
    return id;
  }

  public void setId(String id) {
    this.id = id;
  }

  public List<KeyValueData> getData() {
    return data;
  }

  public void setData(List<KeyValueData> data) {
    this.data = data;
  }
}

public class KeyValueData {

  @JacksonXmlProperty(isAttribute = true, namespace = "http://www.w3.org/2001/XMLSchema-instance")
  private String type;
  @JacksonXmlProperty
  private String key;
  @JacksonXmlProperty
  private String value;

  public KeyValueData(){}

  public String getKey() {
    return key;
  }

  public void setKey(String key) {
    this.key = key;
  }

  public String getValue() {
    return value;
  }

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

  public String getType() {
    return type;
  }

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

}

The code i am using for mapping:

XmlMapper mapper = new XmlMapper();

mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
Customer initiatePaymentRequest = mapper.readValue(xmlString, Customer.class);

logger.info(mapper.writeValueAsString(initiatePaymentRequest));

This results in the following XML output with incorrect namespacing

<Customer>
  <id>123</id>
  <dataList>
    <data wstxns1:type="keyValuePair" xmlns:wstxns1="http://www.w3.org/2001/XMLSchema-instance">
      <key>key1</key>
      <value>val1</value>
    </data>
    <data wstxns2:type="keyValuePair" xmlns:wstxns2="http://www.w3.org/2001/XMLSchema-instance">
      <key>key2</key>
      <value>val2</value>
    </data>
  </dataList>
</Customer>

How do i add the "http://example.com" namespace and have "xsi" prefix instead of wstxns1, wstxns2...

Upvotes: 2

Views: 1857

Answers (0)

Related Questions