java REST - 如何使用 Jersey 传递参数中的 long 数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4878043/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 08:26:35  来源:igfitidea点击:

REST - How to pass an array of long in parameter with Jersey?

javarestjax-wsjersey

提问by Barnouille

I am trying to pass an array of long with Jersey :

我试图通过 Jersey 传递一个 long 数组:

In the client side i have trying something like that :

在客户端,我尝试了类似的方法:

@GET
@Consume("text/plain")
@Produces("application/xml)
Response getAllAgentsById(@params("listOfId") List<Long> listOfId);

Is there a way to realize something like that?

有没有办法实现这样的事情?

Thanks in advance!

提前致谢!

回答by Brian Clozel

If you want to stick to "application/xml" format and avoid JSON format, you should wrap this data into a JAXB annotated object, so that Jersey can use the built-in MessageBodyWriter/ MessageBodyReader.

如果您想坚持“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; 
 }

}

On the client side (using Jersey client)

在客户端(使用 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);

回答by uncaught_exceptions

If you just need to pass array of long its possible without any problem. But I will probably pass the long as comma delimited string. (123,233,2344,232) and then split the string and convert in to long.

如果您只需要传递 long 数组,则可能没有任何问题。但我可能会传递以逗号分隔的长字符串。(123,233,2344,232) 然后拆分字符串并转换为long。

If not, I suggest you use Json Serialization. If you are using java client, then google gson is a good option. In client side, I will encode my list:

如果没有,我建议您使用 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);

And pass this string as post param. In the server side, I will decode like this.

并将此字符串作为 post 参数传递。在服务器端,我会像这样解码。

 Type collectionType = new TypeToken<List<Long>>() {
        } // end new
                .getType();
        List<Long> longList = new Gson().fromJson(longString,
                collectionType);