John Little
John Little

Reputation: 12343

java jackson XML - how to ignore outer wrappers when parsing?

The XML response from the API, I want to parse is something like this:

<Envelope>
   <Body>
      <RESULT>
          <SUCCESS>TRUE</SUCCESS>
          <EMAIL>[email protected]</EMAIL>
          ... more stuff...
      </RESULT>
   </Body>
</Envelope>

I want to get the fields of RESULT into an object.

I could create 3 classes, once for the envelope with the body in it, one for the body with the result in it, and one for the result. But, is there a shortcut?

E.g. just create an object for the result data like this:

@JacksonXmlRootElement(localName = "Envelope/Body/RESULT")
public class Result {
    @JacksonXmlProperty(localName = "SUCCESS")
    private boolean success;
    @JacksonXmlProperty(localName = "EMAIL")
    private String Email;
    :
}

I would do the parsing in a line like this:

return theXmlMapper.readValue(resultPayload, Result.class);

Upvotes: 2

Views: 2547

Answers (1)

Michał Ziober
Michał Ziober

Reputation: 38655

You can read XML as tree, find required node and convert it using treeToValue method. Example:

XmlMapper xmlMapper = new XmlMapper();
xmlMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);

JsonNode root = xmlMapper.readTree(xmlFile);
JsonNode node = root.at("/Body/RESULT");
Result result = xmlMapper.treeToValue(node, Result.class);

TRUE value is not by default parsed as Boolean so you need to write custom deserialiser.

This solution has limitations which @M. Justin points in his comment:

Per the Jackson XML dataformat documentation, "Tree Model is only supported in limited fashion and its use is recommended against: since tree model is based on JSON information model, it does not match XML infoset". This means that the readTree approach should generally not be used when parsing XML. For instance, the tree model will drop repeated elements with the same name, e.g. when using them to model a list such as:

<items><item><id>1</id></item><item><id>2</id></item></items>

Upvotes: 5

Related Questions