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

I am trying to pass an array with jersey:

On the client side, I am trying something like this:

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

Is there a way to implement something like this?

Thanks in advance!

+4
source share
2 answers

If you want to stick to the "application / xml" format and avoid the JSON format, you must wrap this data in an annotated JAXB object so that Jersey can use the built-in 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; } } 

Client side (using 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); 
+2
source

If you just need to pass an array of its longest possible without any problems. But I probably pass a long comma-separated string. (123,233,2344,232) and then split the string and convert it to long.

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

  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 line as post param. On the server side, I will decode like this.

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

Source: https://habr.com/ru/post/1338136/


All Articles