关于如何将 XML 转换为 Java pojo 的小问题。
我有一个 super 简单但有效的 xml:
<results preview='0'>
<messages>
<msg type="TEST">Why this is failing</msg>
</messages>
</results>
为了将其转换为 Java pojo,我准备了以下代码片段:
public static void main( String[] args ) throws Exception {
ObjectMapper objectMapper = new XmlMapper();
String sss =
"<results preview='0'>\n" +
" <messages>\n" +
" <msg type=\"TEST\">Why this is failing</msg>\n" +
" </messages>\n" +
"</results>";
final MyPojo response = objectMapper.readValue(sss, MyPojo.class);
System.out.println(response);
}
使用这个 Java pojo:
public class MyPojo {
private String preview;
private Messages messages;
//get set
public class Messages {
private Msg msg;
//get set
public class Msg {
private String code;
private String type;
//get set
然而,当我运行时,我得到:
Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "" (class io.monitoring.Msg), not marked as ignorable (2 known properties: "type", "code"])
at [Source: (StringReader); line: 3, column: 51] (through reference chain: io.monitoring.MyPojo["messages"]->io.monitoring.Messages["msg"]->io.monitoring.Msg[""])
我可以知道如何解决这个问题吗? 我对解决异常以及获取所有元素感兴趣,希望获得预览 = 0、类型 = TEST,最重要的是实际消息:为什么失败
谢谢
最佳答案
您需要告诉 xmlMapper
哪个字段是属性,哪个字段是值。请使用下面的注释
@JacksonXmlText
用于您的代码,@JacksonXmlProperty(isAttribute = true)
用于 Msg 类中的类型。像下面这样,
public class Msg {
@JacksonXmlText
private String code;
@JacksonXmlProperty(isAttribute = true)
private String type;
public String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
关于Java - com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException : Unrecognized field "" not marked as ignorable,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67430693/