gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 04:11:26 34 4
gpt4 key购买 nike

你能帮我解析下面的 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 的列表。您知道如何解决吗?

EDIT 通过答案编辑解析后的跟踪:

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

最佳答案

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

1。该模型不适合 XML 负载。

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

2。 jackson 注释。

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

更多信息,请阅读:

关于java - Jackson 将 XML 中的平面数组反序列化为 Pojo 列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54872538/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com