Jackson XML 将单个 XML 标签反序列化为对象

Jackson XML Deserialize single XML tag to Object

我想反序列化这个 xml 标签:

<source>Test</source>

变成一个对象(有些javaclass)。

我有下一个class:

public class SomeXml{
  private String source;
}

我正在用 Jackson 的这种方式进行反序列化 XML:

XmlMapper mapper = new XmlMapper();
SomeXml data = mapper.readValue("<source>Test</source>", SomeXml.class);
System.out.println(data);

但它给了我下一个错误:

com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "" (class com.test.SomeXml), not marked as ignorable (one known property: "source"]) at [Source: (StringReader); line: 1, column: 31] (through reference chain: com.test.SomeXml[""])

¿那么我如何将单个 xml 标记反序列化为 object/pojo?

感谢任何帮助!!

那 XML 它是一个 String,而不是一个对象(对于 Jackson).. 相反你应该用另一个包含那个字符串的标签(那将是你的对象)包围它(那将是属性)

XmlMapper mapper = new XmlMapper();
SomeXml data = mapper.readValue("<myObj><source>Test</source></myObj>", SomeXml.class);
System.out.println(data);

要检查我之前所说的内容,您可以检查此代码是否正常工作:

XmlMapper mapper = new XmlMapper();
String data = mapper.readValue("<source>Test</source>", String.class);
System.out.println(data);