杰克逊:反序列化XML在列表中提供了太多元素

时间:2019-08-16 11:14:23

标签: java xml jackson jackson-dataformat-xml

尝试反序列化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-xml2.8.10

1 个答案:

答案 0 :(得分:1)

您不需要包装器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'}}]