我需要构建一个解析器来将 XML
文件解析为 Java
对象。
我使用 Jackson
来执行此操作,并按照 THIS 教程中提供的步骤进行操作。
本教程中有一节“操作 XML 中的嵌套元素和列表”。我遵循了它,但不幸的是我无法获得所有所需元素的所需输出 - 我想输出所有作者的第一个和最后一个。我只在 XML
文件中为我的最后一位作者获取它,如下所示:
[{nameList={person={first=Karl, last=S}}}]
我的 XML
文件如下所示。
<sources>
<Doi>123456789</Doi>
<Title>Title</Title>
<author>
<editor>
<nameList>
<person>
<first>Peter</first>
<last>Parker</last>
</person>
</nameList>
</editor>
</author>
<Source>
<SourceType>Book</SourceType>
<ShortTitle>Book Title</ShortTitle>
<Author>
<Editor>
<NameList />
</Editor>
</Author>
</Source>
<author>
<bookAuthor>
<nameList>
<person>
<first>Karl</first>
<last>S</last>
</person>
</nameList>
</bookAuthor>
</author>
<Source>
<SourceType>Journal</SourceType>
<ShortTitle>ABC Journal</ShortTitle>
</Source>
</sources>
如何反序列化整个 XML 文件?
我的代码如下所示: MyClass.java
private static void jacksonXmlFileToObject() throws IOException {
System.out.println("jacksonXmlFileToObject");
InputStream xmlFile = Publication.class.getClassLoader().getResourceAsStream("test.xml");
ObjectMapper mapper = new XmlMapper();
// Configure
mapper
.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
try {
Sources deserializedData = mapper.readValue(xmlFile, Sources.class);
System.out.println(deserializedData);
} catch (IOException e) {
e.printStackTrace();
}
}
来源.java
@EqualsAndHashCode
@JacksonXmlRootElement(localName = "sources") public class Sources {
@JacksonXmlElementWrapper(localName = "author")
@Getter
@Setter
private Object[] author;
@Override
public String toString() {
return Arrays.toString(author);
}
public Sources() {
}
}
如果能得到一些帮助,我会非常高兴。
谢谢!
最佳答案
使用 JsonMerge
注释。
我自己最近也遇到了类似的问题,发现注解@JsonMerge
解决了这个问题。
我稍微简化了 XML:
<sources>
<author>
<name>Jack</name>
</author>
<source>
<type>Book</type>
</source>
<author>
<name>Jill</name>
</author>
<source>
<type>Journal</type>
</source>
</sources>
使用类 Author
和 Source
class Author {
String name;
}
class Source {
String type;
}
Sources
类如下所示:
class Sources {
// We prevent each <author> tag to be wrapped in an <authors> container tag
@JacksonXmlElementWrapper(useWrapping = false)
// Each element is <author> and not <authors> (and we named our field 'authors')
@JacksonXmlProperty(localName = "author")
// This is the property which solves your problem. It causes non-subsequent elements with the
// same name to be merged into the existing list
@JsonMerge
private List<Author> authors;
@JacksonXmlElementWrapper(useWrapping = false)
@JacksonXmlProperty(localName = "source")
@JsonMerge
private List<Source> sources;
}
关于java - 如何在 Jackson 中反序列化多个嵌套元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57251726/