杰克逊将XML中的平面数组反序列化为Pojo列表

时间:2019-02-25 18:27:39

标签: java jackson pojo jackson-databind jackson-dataformat-xml

您能帮我解析以下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 ElementXML的列表中。你知道如何解决吗?谢谢你的建议。

根据答案进行了简化的解析后编辑跟踪

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$1.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$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.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

2 个答案:

答案 0 :(得分:1)

不可能仅通过一个POJO类对给定的XML内容建模。 您将需要几个POJO类来正确地对XML内容进行建模。

要为f根元素建模,您需要一个类,我们将其称为%hhX

<dataset>

注意上面的代码

  • Dataset属性用@JsonFormat注释,以指定 要使用的日期时间格式
  • @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; } 带有@JacksonXmlElementWrapper(useWrapping = false)的注释 告诉解析器不要期望date
  • 序列周围的多余包装

接下来,您需要一个用于对elements之间的XML内容进行建模的类, 非常类似于您的<element>类。

<element>...</element>

请注意,在上面的代码中,您需要对ElementXML属性进行建模 更复杂。 因为XML内容看起来不像@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

最后,这是<regdate><date>2017-10-25T09:13:54+02:00</date></regdate>类,用于对XML内容进行建模 在RegDate之间。

RegDate

再次注意使用<regdate>...</regdate>指定日期时间格式。

使用上面的类,您可以像这样解析XML

@Getter
@Setter
public class RegDate {

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

答案 1 :(得分:1)

您的问题有些棘手,因为您需要解决一些问题。让我们开始一个一个地解决它们。

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开始。由于我们正在使用它,因此可以指示它为ISO_DATE_TIME类使用LocalDateTime格式。在其他答案中,您可以找到使用JsonFormat注释的示例。这也是一个很好的解决方案,但是当所有日期都具有相同的格式时,更容易定义日期。

有关更多信息,请阅读: