尝试反序列化XML,例如:

<?xml version="1.0" encoding="UTF-8"?>
<Items>
    <Item>
        <Element>
            <Link uri="urn:1">TestLC</Link>
        </Element>
        <Element2>
            <Link>link</Link>
        </Element2>
    </Item>
</Items>

使用代码:
@JacksonXmlRootElement(localName = "Items")
@Data
@NoArgsConstructor
public class ItemInfo {

    @JacksonXmlProperty(localName = "Item")
    @JacksonXmlElementWrapper(useWrapping = false)
    private List<Item> items;

    @Data
    @NoArgsConstructor
    public static class Item {
        @JacksonXmlProperty(localName = "Element")
        private Element element;
    }

    @Data
    @NoArgsConstructor
    public static class Element {
        @JacksonXmlProperty(localName = "Link")
        private String link;
    }

    public static void main(String[] args) throws IOException {
        String xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
                + "<Items>"
                + "    <Item>"
                + "        <Element>"
                + "            <Link uri=\"urn:1\">TestLC</Link>"
                + "        </Element>"
                + "        <Element2>"
                + "            <Link>link</Link>"
                + "        </Element2>"
                + "    </Item>"
                + "</Items>";

        XmlMapper xmlMapper = new XmlMapper();
        xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        ItemInfo itemInfo = xmlMapper.readValue(xml, ItemInfo.class);
        System.out.println(itemInfo.getItems().size());
    }
}

我期望输出1,这是一种itemInfo,其中items包含一个元素,该元素对应于单个<Item>标记。

但是输出是2。解析器以某种方式认为存在两个<Item>
我不明白这是怎么回事,哪里错了。例如,如果我删除属性uri,结果将与预期的一样。
itemInfo.getItems()的内容:

[ItemInfo.Item(element = ItemInfo.Element(link = TestLC)),
ItemInfo.Item(element = null)]

我正在使用jackson-dataformat-xml版本2.8.10

最佳答案

您不需要包装ItemInfo,因为我们可以将其视为Item元素的包装。您可以将代码简化为:

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import java.io.File;
import java.util.Arrays;

public class XmlApp {

  public static void main(String[] args) throws Exception {
    File xmlFile = new File("./resources/test.xml");

    XmlMapper xmlMapper = new XmlMapper();
    xmlMapper.setDefaultUseWrapper(true);
    xmlMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

    Item[] itemInfo = xmlMapper.readValue(xmlFile, Item[].class);
    System.out.println(Arrays.toString(itemInfo));
  }
}

class Item {
  @JacksonXmlProperty(localName = "Element")
  private Element element;

  // getters, setters, toString
}

class Element {
  @JacksonXmlProperty(localName = "Link")
  private String link;

  // getters, setters, toString
}

上面的代码打印:
[Item{element=Element{link='TestLC'}}]

10-06 06:23