[英]Java - com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "" not marked as ignorable
Small question regarding how to convert an XML into a Java pojo please.关于如何将 XML 转换为 Java pojo 的小问题。
I have a super simple, yet valid xml:我有一个超级简单但有效的 xml:
<results preview='0'>
<messages>
<msg type="TEST">Why this is failing</msg>
</messages>
</results>
In order to convert it into a Java pojo, I prepared this snippet:为了将其转换为 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);
}
with this Java pojo:有了这个 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
Yet, when I run, I am getting:然而,当我跑步时,我得到:
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[""])
May I know how to resolve this please?请问我可以知道如何解决这个问题吗? I am interested in solving the Exception, as well as getting all the elements, would like to get preview = 0, type = TEST, and most of all, the actual message: Why this is failing
我有兴趣解决异常以及获取所有元素,希望获得 preview = 0,type = TEST,最重要的是实际消息:为什么这会失败
Thank you谢谢
I think the exception tells you pretty precisely, what is wrong: Your Msg-Class has a field code
which is not contained in the xml.我认为异常非常准确地告诉你,出了什么问题:你的 Msg-Class 有一个域
code
,它不包含在 xml 中。 In order to parse this xml you would probably have to annotate the code
-field with something like "ignore" (sorry - I don't know this now from the top of my head how this is called exactly).为了解析这个 xml 你可能不得不用类似“忽略”的东西来注释
code
字段(对不起 - 我现在不知道这个是如何准确调用的)。
You need to tell the xmlMapper
which field is attribute and which is value.您需要告诉
xmlMapper
哪个字段是属性,哪个是值。 Please use below annotations for that @JacksonXmlText
for your code and @JacksonXmlProperty(isAttribute = true)
for type in Msg class.请为您的代码使用
@JacksonXmlText
和@JacksonXmlProperty(isAttribute = true)
的以下注释以输入Msg class。 Something like below,像下面这样的东西,
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;
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.