使用 JAXB 解组/编组 List<String> [英] Using JAXB to unmarshal/marshal a List&lt;String&gt;

查看:50
本文介绍了使用 JAXB 解组/编组 List<String>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个非常简单的 REST 服务器.我只有一个将返回字符串列表的测试方法.代码如下:

<前><代码>@得到@Path("/test2")公共列表 test2(){列表 list=new Vector();list.add("a");list.add("b");退货清单;}

它给出了以下错误:

<前>SEVERE:Java 类型的消息正文编写器,类 java.util.Vector 和 MIME 媒体类型,应用程序/八位字节流,未找到

我希望 JAXB 对简单类型(如 String、Integer 等)有一个默认设置.我想不是.这是我的想象:

<代码><字符串><字符串>一个<字符串>b

使这种方法奏效的最简单方法是什么?

解决方案

我使用了@LiorH 的例子并将其扩展为:

<前><代码>@XmlRootElement(name="List")公共类 JaxbList{保护列表列表;公共 JaxbList(){}公共 JaxbList(List list){this.list=list;}@XmlElement(name="项目")公共列表 getList(){退货清单;}}

请注意,它使用泛型,因此您可以将它与 String 以外的其他类一起使用.现在,应用程序代码很简单:

<前><代码>@得到@Path("/test2")公共 JaxbList test2(){列表 list=new Vector();list.add("a");list.add("b");返回新的 JaxbList(list);}

为什么 JAXB 包中不存在这个简单的类?有人在其他地方看到过类似的东西吗?

I'm trying to create a very simple REST server. I just have a test method that will return a List of Strings. Here's the code:


@GET
@Path("/test2")
public List test2(){
    List list=new Vector();
    list.add("a");
    list.add("b");
    return list;
}

It gives the following error:

SEVERE: A message body writer for Java type,
class java.util.Vector, and MIME media type,
application/octet-stream, was not found

I was hoping JAXB had a default setting for simple types like String, Integer, etc. I guess not. Here's what I imagined:


<Strings>
  <String>a</String>
  <String>b</String>
</Strings>

What's the easiest way to make this method work?

解决方案

I used @LiorH's example and expanded it to:


@XmlRootElement(name="List")
public class JaxbList<T>{
    protected List<T> list;

    public JaxbList(){}

    public JaxbList(List<T> list){
        this.list=list;
    }

    @XmlElement(name="Item")
    public List<T> getList(){
        return list;
    }
}

Note, that it uses generics so you can use it with other classes than String. Now, the application code is simply:


    @GET
    @Path("/test2")
    public JaxbList test2(){
        List list=new Vector();
        list.add("a");
        list.add("b");
        return new JaxbList(list);
    }

Why doesn't this simple class exist in the JAXB package? Anyone see anything like it elsewhere?

这篇关于使用 JAXB 解组/编组 List<String>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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