Learner
Learner

Reputation: 2339

How to return Array in Jersey REST webservice?

I am new to REST webservice, I tried using Jersey implementation and wrote a simple webservice code to return List to calling client:

@GET
@Produces(MediaType.TEXT_XML)
public GenericEntity<List<String>> stringlist() {
    List<String> list = Arrays.asList("test", "as");
    return new GenericEntity<List<String>>(list) {
    };
}

I am not sure how to get the value of the list in my client. I just tried using the below code in my client but I am getting error.

service.path("rest")
       .path("getVal")
       .accept(MediaType.TEXT_XML)
       .get(GenericEntity.class

Can someone help me with a simple webservice code which passes the Array to client?

Upvotes: 1

Views: 5138

Answers (1)

Pavel Bucek
Pavel Bucek

Reputation: 5324

You should be able to return just List of some @XmlRootElement annotated objects and access them:

service.path("rest").path("getVal").accept(MediaType.TEXT_XML).get(new GenericEntity<List<MyObj>>{});

for some reason this is more complicated with plain strings, you need to encapsulate them with JAXBElement

@GET
@Produces(MediaType.TEXT_XML)
public List<JAXBElement<String>> stringlist() {
     Arrays.asList(new JAXBElement[] {
        new JAXBElement(QName.valueOf("element1"), String.class, "ahoj"),
        new JAXBElement(QName.valueOf("element2"), String.class, "nazdar")
    };);
}

And access it similarly as in previous case, but you would need to "ask" for

new GenericEntity<List<JAXBElement<String>>>{}

Upvotes: 2

Related Questions