簡體   English   中英

Java - com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException:無法識別的字段“”不可標記

[英]Java - com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "" not marked as ignorable

關於如何將 XML 轉換為 Java pojo 的小問題。

我有一個超級簡單但有效的 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[""])

請問我可以知道如何解決這個問題嗎? 我有興趣解決異常以及獲取所有元素,希望獲得 preview = 0,type = TEST,最重要的是實際消息:為什么這會失敗

謝謝

我認為異常非常准確地告訴你,出了什么問題:你的 Msg-Class 有一個域code ,它不包含在 xml 中。 為了解析這個 xml 你可能不得不用類似“忽略”的東西來注釋code字段(對不起 - 我現在不知道這個是如何准確調用的)。

您需要告訴xmlMapper哪個字段是屬性,哪個是值。 請為您的代碼使用@JacksonXmlText@JacksonXmlProperty(isAttribute = true)的以下注釋以輸入Msg class。 像下面這樣的東西,

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM