简体   繁体   中英

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

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

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!

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 .

@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)

// 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);

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.

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:

  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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM