I have such code
public class Xml {
public static void main(String[] args) throws JsonProcessingException {
String xmlString = "<password><plainPassword>12345</plainPassword></password>";
XmlMapper xmlMapper = new XmlMapper();
PlainPassword plainPassword = xmlMapper.readValue(xmlString, PlainPassword.class);
System.out.println(plainPassword.getPlainPassword());
}
@JacksonXmlRootElement(localName = "password")
public static class PlainPassword {
public String getPlainPassword() {
return this.plainPassword;
}
public void setPlainPassword(String plainPassword) {
this.plainPassword = plainPassword;
}
private String plainPassword;
}
}
It works fine, but in xmlString
I can use any root tag name and my code still will work.
For example String xmlString = "<x><plainPassword>12345</plainPassword></x>";
where I use x
as root element also works.
But is it possible to say xmlMapper that it could correctly deserialize only strings with "password" root element?
Unfortunately, the behavior you described is the one supported by Jackson as indicated in this Github open issue.
With JSON content and
ObjectMapper
you can enable theUNWRAP_ROOT_VALUE
deserialization feature, and maybe it could be of help for this purpose, although I am not quite sure if this feature is or not correctly supported byXmlMapper
.One possible solution could be the implementation of a custom deserializer.
Given your
PlainPassword
class:Consider the following
main
method:Where the custom deserializer looks like:
You have to implement
ResolvableDeserializer
when modifyingBeanDeserializer
, otherwise deserializing throws exception.The code is based in this excellent SO answer.
The test should raise
IllegalArgumentException
with the corresponding message:Please, modify the exception type as appropriate.
If, instead, you use:
in your
main
method, it should run without problem.