简体   繁体   中英

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.

I have a super simple, yet valid 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:

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:


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

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. 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).

You need to tell the xmlMapper which field is attribute and which is value. Please use below annotations for that @JacksonXmlText for your code and @JacksonXmlProperty(isAttribute = true) for type in 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;
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM