使用JAXB解组时将空元素转换为null [英] Transforming empty element into null when unmarshalling with JAXB
问题描述
使用以下JAXB注释定义类:
class Course {
@XmlElement(name = book)
List< Book> requiredBooks = new ArrayList< Book>();
当解组包含此
的XML文档时pre>
<当然>
...
< book />
< / course>
我最终将一本书添加到列表中,其所有属性都设置为null。我不控制XML输入。如何防止添加此空白书?我尝试拦截set ..()或添加..()方法,但是在处理集合时,JAXB绕过了setter。有什么建议吗?
这是 工作的解决方案。同样,优雅被遗忘。
JAXB定义了两个回调:beforeUnmarshal和afterUnmarshal。通过实现afterUnmarshal来清理列表,我能够达到预期的结果。
class课程
{
@XmlElement(name =book)
List< Book> requiredBooks = new ArrayList< Book>();
...
void afterUnmarshal(Unmarshaller aUnmarshaller,Object aParent)
{
if(requiredBooks!= null)
{
Iterator< Book> iterator = requiredBooks.iterator();
while(iterator.hasNext())
{
Book book = iterator.next();
if(StringUtils.isEmpty(book.getTitle()))
{
//没有标题的书被视为无效
iterator.remove();
}
}
}
}
}
虽然这有效,但最大的问题是没有用于实现afterUnmarshal的接口。它是由JAXB使用反射查找的,但我认为如果JAXB只提供接口和/或抽象实现,那将会很方便(并且会减少调试/维护)。如果是,如果afterUnmarshal的签名将来会发生什么变化呢?这段代码将神秘地停止工作,因为它应该是。
A class is defined with the following JAXB annotation:
class Course {
@XmlElement (name = "book")
List<Book> requiredBooks = new ArrayList<Book>();
When unmarshalling an XML document that contains this
<course>
...
<book/>
</course>
I end up with a Book added to the list, with all of its attributes set to null. I don't control the XML input. How can I prevent this empty book from being added? I tried intercepting in set..() or add..() methods, but turns out JAXB bypasses setters when dealing with collections. Any suggestions?
Here's a solution that does work. Again, elegance was left behind.
There are two callbacks defined by JAXB: beforeUnmarshal and afterUnmarshal. By implementing afterUnmarshal to clean up the list, I was able to achieve the desired result.
class Course
{
@XmlElement (name = "book")
List<Book> requiredBooks = new ArrayList<Book>();
...
void afterUnmarshal(Unmarshaller aUnmarshaller, Object aParent)
{
if (requiredBooks != null)
{
Iterator<Book> iterator = requiredBooks.iterator();
while (iterator.hasNext())
{
Book book = iterator.next();
if (StringUtils.isEmpty(book.getTitle()))
{
// a book without title is considered invalid
iterator.remove();
}
}
}
}
}
While this works, by biggest issue with it is the absence of an interface for implementing afterUnmarshal. It's looked up by JAXB using reflection, but I think it would've been convenient (and would reduce debugging/maintenance) if JAXB simply supplied interfaces and/or absract implementations. As it is, what if the signature of afterUnmarshal changes in the future? This code will just mysteriously stop working as it's supposed to.
这篇关于使用JAXB解组时将空元素转换为null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!