我如何用JAXB编组java.util.List,如JAX-RS(CXF和Jersey) [英] How do I marshal java.util.List with JAXB like JAX-RS (CXF, and Jersey) do

查看:180
本文介绍了我如何用JAXB编组java.util.List,如JAX-RS(CXF和Jersey)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎最新的JAX-RS可以处理将java.util.List作为XMLRootElement返回的方法,但普通的JAXB不能。
我想模仿CXF和泽西岛正在做的事情。



换句话说,我想列出一个名单,就像CXF和泽西一样。
通常,如果您尝试使用JAXB封送列表,则会获得根元素异常。
如何在不必制作包装物的情况下解决这个问题?



编辑:谢谢你的答案,但我很熟悉使用@XmlElementWrapper但是它甚至没有接近模拟JAX-RS正在做什么。



JAX-RS执行此操作:

  @XmlRootElement(name =dog)
public class Dog {
private String name;
public String getName(){return this.name; }
// Setter也是
}

现在如果我序列化一个列表狗:

 序列化(List< Dog> dogs); 

XML应该是(JAX-RS的作用):

 < dogs> 
< dog>< name> Rascal< / name>< / dog>
< / dogs>

所以你可以看到我不想为每个域对象创建一个包装器对象。

解决方案

Blaise Doughan我相信这里显示了一个很好的解决方案:是否可以通过编程方式配置JAXB?





http://blog.bdoughan.com/2012/11/creating-generic-list-wrapper-in-jaxb.html



<虽然在某种程度上稍有不同的用例:



http://blog.bdoughan.com/2012/02/xmlanyelement-and-xmladapter.html


It seems the latest JAX-RS can handle methods returning java.util.List as the XMLRootElement but normal JAXB cannot. I would like to mimic what CXF and Jersey are doing.

In other words I would like to Marshal a List and just like CXF and Jersey do. Normally if you try to marshal a list with JAXB you get the Root Element exception. How do I get around this with out having to make a wrapping object?

EDIT: Thanks for the many answers but I'm very familiar with the @XmlElementWrapper but that does not even come close to simulating what JAX-RS is doing.

JAX-RS does this:

@XmlRootElement(name="dog")
public class Dog {
    private String name;
    public String getName() { return this.name; }
    //Setter also
}

Now if I serialize a list of dogs:

serialize(List<Dog> dogs);

XML should be (what JAX-RS does):

<dogs>
    <dog><name>Rascal</name></dog>
</dogs>

So you can see I don't want to have to make a wrapper object for every single domain object.

解决方案

Blaise Doughan I believe shows a good solution for this problem here: Is it possible to programmatically configure JAXB?

and

http://blog.bdoughan.com/2012/11/creating-generic-list-wrapper-in-jaxb.html

and somewhat here albeit slightly different use case:

http://blog.bdoughan.com/2012/02/xmlanyelement-and-xmladapter.html

这篇关于我如何用JAXB编组java.util.List,如JAX-RS(CXF和Jersey)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆