JAXB:当返回类型是接口时,如何使用字段名称进行编组?
如果我有一个类 (A),其中包含多个相同类型的属性(接口 B)。
public interface B {...}
public class A {
...
@XmlAnyElement
public B getFirstB(){...}
@XmlAnyElement
public B getSecondB(){...}
}
// some concrete implementations of B
@XmlRootElement
public class BImpl implements B {...}
@XmlRootElement
public class AnotherBImpl implements B {...}
我得到以下信息:
<a>
<bImpl/>
<anotherBImpl/>
</a>
但我想区分属性。如何获取:
<a>
<firstB>
<bImpl/>
</firstB>
<secondB>
<anotherBImpl/>
</secondB>
</a>
由于属性不是集合,因此我无法使用@XmlElementWrapper。
如果可以避免的话,我真的不想更改代码。
任何想法表示赞赏。 JAXB 中的编组似乎非常棘手。
If I have a class (A) that contains several properties of the same type (interface B).
I've used the suggestion in http://jaxb.java.net/guide/Mapping_interfaces.html to use a combination of @XmlRootElement and @XmlAnyElement to get around the interface problem:
public interface B {...}
public class A {
...
@XmlAnyElement
public B getFirstB(){...}
@XmlAnyElement
public B getSecondB(){...}
}
// some concrete implementations of B
@XmlRootElement
public class BImpl implements B {...}
@XmlRootElement
public class AnotherBImpl implements B {...}
I get the following:
<a>
<bImpl/>
<anotherBImpl/>
</a>
But I want to distinguish between the properties. How do I get:
<a>
<firstB>
<bImpl/>
</firstB>
<secondB>
<anotherBImpl/>
</secondB>
</a>
As the properties are not collections, I can't use @XmlElementWrapper.
I don't really want to change the code if avoidable.
Any thoughts appreciated. Marshalling in JAXB seems to be very tricky.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
将
@XmlAnyElement
替换为@XmlElement(type = Object.class)
。这将区分各个字段。有关此解决方案的更多详细信息,请参阅我对相关问题的回答。
Replace
@XmlAnyElement
with@XmlElement(type = Object.class)
. This will distinguish individual fields.More details on this solution in my answer to a related question.
您无法在 JAXB 中封送接口。解组器如何知道如何实例化您的接口?
检查这个,它有一个非常好的解释。
You cannot marshal interfaces in JAXB. How would the unmarshaller know how to instantiate your interface?
Check this out, it has a really nice explanation.
我认为,在你的情况下不会发生任何魔法。使用简单的包装类(对于经典 JAXB)或使用
@XmlPath
(对于 MOXy)(感谢 Blaise Doughan)。I think, no magic can happen in your case. Either use a simple wrapper class (for classic JAXB) or use
@XmlPath
(for MOXy) (acknowledgements to Blaise Doughan).