如何返回Java List< String> Json使用Jax-RS [英] How do return Java List<String> Json using Jax-RS
问题描述
我想知道如何返回一个List的JSON数组,例如:
@GET
@Produces(application / json)
public List< String> aMethod(){
返回Array.asList(text1,text2,text3);
}
我想知道,如何接收List参数类型我的方法,例如
@PUT
@Consumes(application / json)void otherMethod(List< String> ;){
//做某事;
}
我读过JaxbContext,我理解它对我有什么帮助。<使用JAXB,支持两种类型的 List
。第一个是元素列表,第二个是分隔字符串(普通XML值或属性,使用某个分隔符将其解析为列表)。第一个似乎是你想要的(数组)。
供参考,参见: http://jaxb.java.net/jaxb20-ed/api/javax/xml/bind/annotation/XmlList.html
您会注意到,在这两种情况下,您需要的List都需要被其他对象封装。从根本上说,XML(以及扩展的JAXB)喜欢将所有内容追溯到单个根节点/对象。所以要建模它,你需要这样的东西:
@XmlRootElement(name =wrapper)
public abstract class ListWrapper {
public List< String>名称;
}
然后你的方法需要改为接受/返回 ListWrapper
对象并从中提取实际的List。
I'd like know how do to a method return a JSON array of List, for example:
@GET
@Produces("application/json")
public List<String> aMethod(){
return Array.asList("text1", "text2", "text3");
}
I'd want to know, how do to receive a List argument type in my method, for example
@PUT
@Consumes("application/json") void otherMethod(List<String>){
// do something ;
}
I've read about JaxbContext, I understanding how it can help me.
With JAXB there are two type's of List
supported. The first is a List of elements, the second a delimited string (a "normal" XML value or attribute, which is parsed into a list using some delimiter). The first seems to be what you want ("array").
For reference, see: http://jaxb.java.net/jaxb20-ed/api/javax/xml/bind/annotation/XmlList.html
You will note that in both cases the List you want would need to be encapsulated by some other object. Fundamentally, XML (and by extension JAXB) likes to trace everything back to a single root node/object. So to model it, you need something like this:
@XmlRootElement(name="wrapper")
public abstract class ListWrapper {
public List<String> names;
}
Then your methods would need to be changed to accept/return ListWrapper
objects and extract the actual List from it.
这篇关于如何返回Java List< String> Json使用Jax-RS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!