将 Jackson XML 中的平面数组反序列化为 Pojo 列表

Deserialize flat array in XML by Jackson to List of Pojo

你能帮我解析以下 XML 文件吗?

<?xml version="1.0" encoding="UTF-8"?>
<dataset xmlns="http:/foo.com">
   <date>2017-10-25T09:13:54+02:00</date>
   <element>
      <id>1</id>
      <name>Stuart</name>
      <age>34</age>
      <regdate><date>2017-10-25T09:13:54+02:00</date></regdate>
   </element>
   <element>
      <id>2</id>
      <name>Lora</name>
      <age>12</age>
      <regdate><date>2017-10-25T09:13:54+02:00</date></regdate>
   </element>
   <element>
      <id>3</id>
      <name>Ben</name>
      <age>50</age>
      <regdate><date>2017-10-25T09:13:54+02:00</date></regdate>
   </element>
</dataset >

我试过这样创建 pojo:

@Getter
@Setter
@JacksonXmlRootElement(localName = "element")
public class ElementXML {
    @JacksonXmlProperty(localName = "id")
    private Long id;    
    @JacksonXmlProperty(localName = "name")
    private String name;
    @JacksonXmlProperty(localName = "age")
    private Long age;
    @JacksonXmlProperty(localName = "regdate")
    private LocalDateTime regdate;
}

我使用的解析机制在这里:

    XMLInputFactory f = XMLInputFactory.newFactory();
    File inputFile = new File("some path");
    XMLStreamReader sr = f.createXMLStreamReader(new FileInputStream(inputFile));


    ObjectMapper xmlMapper = new XmlMapper();

我卡住了,因为我不知道如何将元素标签解析到我创建的 pojo 元素列表中XML。你知道如何解决吗?谢谢指教。

在按答案编辑解析后编辑跟踪

com.fasterxml.jackson.databind.JsonMappingException: Expected END_ELEMENT, got event of type 1 (through reference chain: com.xml.Dataset["element"]->java.lang.Object[][1])

    at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:394)
    at com.fasterxml.jackson.databind.JsonMappingException.wrapWithPath(JsonMappingException.java:365)
    at com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer.deserialize(ObjectArrayDeserializer.java:206)
    at com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer.deserialize(ObjectArrayDeserializer.java:21)
    at com.fasterxml.jackson.databind.deser.impl.MethodProperty.deserializeAndSet(MethodProperty.java:127)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:288)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
    at com.fasterxml.jackson.dataformat.xml.deser.WrapperHandlingDeserializer.deserialize(WrapperHandlingDeserializer.java:113)
    at com.fasterxml.jackson.databind.ObjectMapper._readMapAndClose(ObjectMapper.java:4013)
    at com.fasterxml.jackson.databind.ObjectMapper.readValue(ObjectMapper.java:2902)
    at com.xml.data.ParseXmlTest.test(ParseXmlTest.java:62)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestExecutionCallbacks.evaluate(RunBeforeTestExecutionCallbacks.java:74)
    at org.springframework.test.context.junit4.statements.RunAfterTestExecutionCallbacks.evaluate(RunAfterTestExecutionCallbacks.java:84)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:251)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:97)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access[=14=]0(ParentRunner.java:58)
    at org.junit.runners.ParentRunner.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:190)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.CommandLineWrapper.main(CommandLineWrapper.java:67)
Caused by: java.io.IOException: Expected END_ELEMENT, got event of type 1
    at com.fasterxml.jackson.dataformat.xml.deser.XmlTokenStream.skipEndElement(XmlTokenStream.java:190)
    at com.fasterxml.jackson.dataformat.xml.deser.FromXmlParser.nextToken(FromXmlParser.java:584)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.vanillaDeserialize(BeanDeserializer.java:283)
    at com.fasterxml.jackson.databind.deser.BeanDeserializer.deserialize(BeanDeserializer.java:151)
    at com.fasterxml.jackson.databind.deser.std.ObjectArrayDeserializer.deserialize(ObjectArrayDeserializer.java:195)
    ... 43 more

无法仅通过一个 POJO class 对给定的 XML 内容进行建模。 您将需要几个 POJO classes 来正确建模您的 XML 内容。

要对 <dataset> 根元素建模,您需要一个 class,我们称它为 Dataset

@Getter
@Setter
@JacksonXmlRootElement(localName = "dataset")
public class Dataset {

    @JacksonXmlProperty(localName = "date")
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ssXXX")
    private LocalDateTime date;

    @JacksonXmlProperty(localName = "element")
    @JacksonXmlElementWrapper(useWrapping = false)
    private List<ElementXML> elements;
}

上面代码中注意

接下来,您需要一个 class 来为 <element>...</element> 之间的 XML 内容建模, 非常喜欢你的 ElementXML class.

@Getter
@Setter
public class ElementXML {

    @JacksonXmlProperty(localName = "id")
    private Long id;

    @JacksonXmlProperty(localName = "name")
    private String name;

    @JacksonXmlProperty(localName = "age")
    private Long age;

    @JacksonXmlProperty(localName = "regdate")
    private RegDate regdate;
}

请注意上面的代码,您需要对 regdate 属性 进行建模 更复杂。 因为 XML 内容看起来不像 <regdate>2017-10-25T09:13:54+02:00</regdate> 您不能简单地将其声明为 LocalDate regdate。 相反 XML 看起来像 <regdate><date>2017-10-25T09:13:54+02:00</date></regdate>。 因此,您需要使用另一个 class 对其进行建模(我们称之为 RegDate

最后,这里是 RegDate class 用于建模 XML 内容 在 <regdate>...</regdate>.

之间
@Getter
@Setter
public class RegDate {

    @JacksonXmlProperty(localName = "date")
    @JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd'T'HH:mm:ssXXX")
    private LocalDateTime date;
}

再次注意使用 @JsonFormat 来指定日期时间格式。

使用上面的 classes 你可以这样解析 XML

    File inputFile = new File("some path");
    ObjectMapper xmlMapper = new XmlMapper();
    xmlMapper.registerModule(new JavaTimeModule());
    Dataset dataset = xmlMapper.readValue(inputFile, Dataset.class);

你的问题有点棘手,因为你需要解决几个问题。让我们开始一一解决吧。

1。模型不适合 XML 负载。

首先,您需要创建适合您 payload 的模型。它不依赖于格式,因为 JSONXML 几乎相同。为此,我建议始终从序列化过程开始。在 Java 中构建模型并尝试序列化它要容易得多。如果它看起来与预期不一样,您需要更新模型。您重复这些步骤:updateserialise 直到找到有效模型。之后你可以反序列化给定 payload 没有任何问题。

2。杰克逊注释。

即便如此Jackson的注解很好,不要无缘无故地使用它们。如果 POJO 属性 与 XML 中的节点名称相同,则不需要添加 JacksonXmlProperty 注释。当 POJOpayload 中的名称不同时,您必须添加它。在其他情况下,这会使 POJO 结构过于复杂。我们应该让它尽可能简单。您需要使用一个棘手的注释:JacksonXmlElementWrapper。当我们有节点集合但它们未包装时使用它。

在这两个简单的段落之后,以免反序列化您的案例。我们需要扩展您的 POJO 结构,它应该如下所示:

class Dataset {

    private LocalDateTime date;

    @JacksonXmlProperty(localName = "element")
    @JacksonXmlElementWrapper(useWrapping = false)
    private List<Element> elements;

    public LocalDateTime getDate() {
        return date;
    }

    public void setDate(LocalDateTime date) {
        this.date = date;
    }

    public List<Element> getElements() {
        return elements;
    }

    public void setElements(List<Element> element) {
        this.elements = element;
    }

    @Override
    public String toString() {
        return "Dataset{" +
                "date=" + date +
                ", element=" + elements +
                '}';
    }
}

class Element {

    private Long id;
    private String name;
    private Long age;
    private RegDate regdate;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Long getAge() {
        return age;
    }

    public void setAge(Long age) {
        this.age = age;
    }

    public RegDate getRegdate() {
        return regdate;
    }

    public void setRegdate(RegDate regdate) {
        this.regdate = regdate;
    }

    @Override
    public String toString() {
        return "ElementXML{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", age=" + age +
                ", regdate=" + regdate.getDate() +
                '}';
    }
}

class RegDate {

    private LocalDateTime date;

    public RegDate() {
        this(null);
    }

    public RegDate(LocalDateTime date) {
        this.date = date;
    }

    public LocalDateTime getDate() {
        return date;
    }

    public void setDate(LocalDateTime date) {
        this.date = date;
    }

    @Override
    public String toString() {
        return "RegDate{" +
                "date=" + date +
                '}';
    }
}

以及用法示例:

import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.dataformat.xml.XmlMapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

public class XmlMapperApp {

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

        JavaTimeModule module = new JavaTimeModule();
        module.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ISO_DATE_TIME));

        XmlMapper xmlMapper = new XmlMapper();
        xmlMapper.registerModule(module);
        xmlMapper.enable(SerializationFeature.INDENT_OUTPUT);

        Dataset dataset = xmlMapper.readValue(jsonFile, Dataset.class);
        dataset.getElements().forEach(System.out::println);
    }
}

以上代码打印:

ElementXML{id=1, name='Stuart', age=34, regdate=2017-10-25T09:13:54}
ElementXML{id=2, name='Lora', age=12, regdate=2017-10-25T09:13:54}
ElementXML{id=3, name='Ben', age=50, regdate=2017-10-25T09:13:54}

以上代码的两条额外注释。当您使用 java.time.* 类 和 Jackson 时,最好从注册来自 jackson-datatype-jsr310 模块的 JavaTimeModule 开始。因为我们正在使用它,所以我们可以指示它对 LocalDateTime 类 使用 ISO_DATE_TIME 格式。在其他答案中,您可以找到使用 JsonFormat 注释的示例。这也是一个很好的解决方案,但是当所有日期都具有相同的格式时,更容易定义它。

有关更多信息,请阅读:

  • How do I update RestTemplate to correctly map Java Dates?