JAXB - 编组到 XML 时可以扁平化类包含吗?
假设,我有两个类:
@XmlRootElement
class A {
@XmlElement
String propertyOfA;
@XmlElement
B b;
}
class B {
@XmlElement
String propertyOfB;
}
JAXB 返回按照以下方式格式化的 XML:
<a>
<propertyOfA>valueA</propertyOfA>
<b>
<propertyOfB>valueB</propertyOfB>
</b>
</a>
我的问题是 如何展平 XML 中的层次结构? 这样我就有:
<a>
<propertyOfA>valueA</propertyOfA>
<propertyOfB>valueB</propertyOfB>
</a>
这可以通过注释来完成吗?
目前,我正在考虑为 A 创建一种包装类,该类将按照我希望在 XML 中查看它们的方式构建字段。有更好的办法吗?
Say, I have two classes:
@XmlRootElement
class A {
@XmlElement
String propertyOfA;
@XmlElement
B b;
}
class B {
@XmlElement
String propertyOfB;
}
JAXB returns an XML formatted in the according way:
<a>
<propertyOfA>valueA</propertyOfA>
<b>
<propertyOfB>valueB</propertyOfB>
</b>
</a>
My question is how to flatten the hierarchy in the XML? So that I have:
<a>
<propertyOfA>valueA</propertyOfA>
<propertyOfB>valueB</propertyOfB>
</a>
Can this be done with annotations?
At the moment I am thinking to create a kind of wrapper class for A, that would have fields built the way I want to see them in the XML. Is there a better way?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
注意:我是EclipseLink JAXB (MOXy) 的领导者和 JAXB 2 的成员(JSR-222)专家组。
您可以使用 MOXy 的
@XmlPath
扩展来映射此用例:了解更多信息
Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB 2 (JSR-222) expert group.
You could use MOXy's
@XmlPath
extension to map this use case:For More Information
这对我来说已经有一段时间了,但让我尝试一下:
编辑:免责声明-我还没有编译或尝试过这个。但我相信这就是你的做法。
It's been a while for me, but let me give it a crack:
Edit: disclaimer- I havn't compiled or tried this. But I believe it's how you do it.
看看这个问题和建议的解决方案: Spring RESTful 客户端:根标签异常
对于解决此类问题非常有帮助。
Take a look to that question and the solution proposed: Spring RESTful client: root tag exception
Very helpful to solve this kind of problem.
另一种方法(使用标准 JAXB)是使用
@XmlJavaTypeAdapter
。通过这种方式,您可以调整对象层次结构,但缺点是必须编写将对象层次结构转换为调整后的新类的代码。然而,在您的示例中,它不起作用,因为您必须调整作为您的根的 A 类。然而,如果层次结构更深,并且您需要使适应比根低一级,那么就不会有问题。一个可能有用的建议是在适应的实体中编写代码,使其像对象层次结构的委托,而不是适配器,这样适配器就会非常薄。
An alternative approach (with standard JAXB) would be using
@XmlJavaTypeAdapter
. This way you could adapt the object hierarchy with the drawback of having to write the code that translates the object hierarchy into the adapted new class.In your example however it wouldn't work as you would have to adapt class A which is your root. If however the hierarchy was deeper and you needed to make the adaptation one level lower than the root, then there wouldn't be a problem. A suggestion that might be useful is to write the code in the adapted entity, making it like a delegate to the object hierarchy, rather than the adapter, which would then be very thin.