0

I am reframing my own question at : Returning a primitive array through REST

I am using Jersey, and I am unable to understand what codes/annotations should be added at both server and client ends to return an "array" of primitives (strings, integers, anything). I can do this very easily in SOAP...isnt there some easy way out in REST ? I got some complex ways of doing this here : how-to-serialize-java-primitives-using-jersey-

A piece of code (both server and client) would be appreciated a lot !

1 Answer 1

2

Wrap the primitive array in a JAXB annotated object. Jersey will use the built-in MessageBodyReader and MessageBodyWriter

E.g.

import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlAccessorType;

@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public IntArray {

 private int[] ints;

 public IntArray() {}

 public IntArray(int[] ints) {
  this.ints = ints;
 }

 public int[] getInts() {
  return ints; 
 } 
 ...
}

On the server side:

@Path("ints")
public class TestResource {

 @GET
 @Produces("application/xml")
 public Response get() {
  int[] ints = {1, 2, 3};
  IntArray intArray = new IntArray(ints);
  return Response.ok(intArray).build();
 } 
}

On the client side:

Client client = new Client();
WebResource wr = client.resource("http://localhost:8080/service");
IntArray intArray = wr.path("/ints").get(IntArray.class);
int[] ints = intArray.getInts();

Try something like that. I didn't test the code, so hopefully it works.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks reverendgreen...but this is not working. I am getting a null value at the client side :(
Strange... I just tested the code and it works great. Can you show a bit of your code? Perhaps myself or someone else can spot the error.
Try your request URI in a browser; if you don't see the expected response, then it's a problem on the server side.
Thanks a lot ! I guess my code was not working as I avoided using @XmlAccessorType(XmlAccessType.FIELD) !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.