使用JAXB解组/编组List< String> [英] Using JAXB to unmarshal/marshal a List<String>
问题描述
我正在尝试创建一个非常简单的REST服务器。我只有一个将返回字符串列表的测试方法。这是代码:
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;
}
它出现以下错误:
SEVERE: A message body writer for Java type,
class java.util.Vector, and MIME media type,
application/octet-stream, was not found
我希望JAXB对String,Integer等简单类型有默认设置。我猜不是。这就是我想象的:
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?
推荐答案
我使用@LiorH的例子并将其扩展为:
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;
}
}
注意,它使用泛型所以您可以将其与String之外的其他类一起使用。现在,应用程序代码很简单:
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);
}
为什么JAXB包中不存在这个简单类?有人在别处看到类似的东西吗?
Why doesn't this simple class exist in the JAXB package? Anyone see anything like it elsewhere?
这篇关于使用JAXB解组/编组List< String>的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!