问题
The XML
response from the API
, I want to parse is something like this:
<Envelope>
<Body>
<RESULT>
<SUCCESS>TRUE</SUCCESS>
<EMAIL>somebody@domain.com</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);
回答1:
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>
来源:https://stackoverflow.com/questions/55522037/java-jackson-xml-how-to-ignore-outer-wrappers-when-parsing