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 !

Community
  • 1
  • 1
dev
  • 11,071
  • 22
  • 74
  • 122

1 Answers1

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.

Jordan Allan
  • 4,408
  • 7
  • 32
  • 35
  • Thanks reverendgreen...but this is not working. I am getting a null value at the client side :( – dev Jan 28 '11 at 17:33
  • 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. – Jordan Allan Jan 28 '11 at 18:45
  • Try your request URI in a browser; if you don't see the expected response, then it's a problem on the server side. – Jordan Allan Jan 28 '11 at 18:53
  • Thanks a lot ! I guess my code was not working as I avoided using @XmlAccessorType(XmlAccessType.FIELD) ! – dev Jan 29 '11 at 05:46