【发布时间】:2011-06-20 04:00:27
【问题描述】:
我正在尝试使用 Jersey 传递一个 long 数组:
在客户端,我尝试过类似的方法:
@GET
@Consume("text/plain")
@Produces("application/xml)
Response getAllAgentsById(@params("listOfId") List<Long> listOfId);
有没有办法实现这样的事情?
提前致谢!
【问题讨论】:
我正在尝试使用 Jersey 传递一个 long 数组:
在客户端,我尝试过类似的方法:
@GET
@Consume("text/plain")
@Produces("application/xml)
Response getAllAgentsById(@params("listOfId") List<Long> listOfId);
有没有办法实现这样的事情?
提前致谢!
【问题讨论】:
如果您想坚持“application/xml”格式并避免使用 JSON 格式,则应将此数据包装到 JAXB 注释对象中,以便 Jersey 可以使用内置的MessageBodyWriter/MessageBodyReader。
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public ListOfIds{
private List<Long> ids;
public ListOfIds() {}
public ListOfIds(List<Long> ids) {
this.ids= ids;
}
public List<Long> getIds() {
return ids;
}
}
在客户端(使用 Jersey 客户端)
// get your list of Long
List<Long> list = computeListOfIds();
// wrap it in your object
ListOfIds idList = new ListOfIds(list);
Builder builder = webResource.path("/agentsIds/").type("application/xml").accept("application/xml");
ClientResponse response = builder.post(ClientResponse.class, idList);
【讨论】:
如果您只需要传递 long 数组,则可能没有任何问题。但我可能会通过逗号分隔的字符串。 (123,233,2344,232) 然后拆分字符串并转换为长字符串。
如果没有,我建议你使用 Json 序列化。如果您使用的是 java 客户端,那么 google gson 是一个不错的选择。在客户端,我将对我的列表进行编码:
List<Long> test = new ArrayList<Long>();
for (long i = 0; i < 10; i++) {
test.add(i);
}
String s = new Gson().toJson(test);
并将此字符串作为 post 参数传递。在服务器端,我会这样解码。
Type collectionType = new TypeToken<List<Long>>() {
} // end new
.getType();
List<Long> longList = new Gson().fromJson(longString,
collectionType);
【讨论】: