Jackson:反序列化 XML 在列表中给出了太多元素

Jackson: deserializing XML gives too many elements in list

正在尝试反序列化 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,即 itemInfoitems 包含一个对应于单个 <Item> 标签的元素。

但是输出是 2。解析器以某种方式认为有两个 <Item>s

我不明白这是怎么回事,哪里出了问题。例如,如果我删除属性 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'}}]