Good Morning. Today morning when I am going through Jersey Entity providers MessageBodyReader
s and MessageBodyWriter
s I came across the following problem.
I want to write a resource method and client that returns a list of custom objects and media type is application/xml
. So I would like to use JAXB (I am new to JAXB). I was able to achieve this by writing my own extended MessageBodyReader
and MessageBodyWriter
. But I am afraid of the way I am following. Just look at the way I implemented:
Resource method:
@Path("productlist/xml")
@GET
public RetObjects getProductsXml(){
List<Product> pList = new ArrayList<Product>();
pList.add(new Product("1","Dell latitude E6000",2900,500));
pList.add(new Product("2","Xperia Z2",549,400));
RetObjects obj = new RetObjects();
obj.setObject(pList);
return obj;
}
My custom objects:
@Entity
@Table (name="PRODUCT")
@XmlRootElement(name="product")
public class Product {
@Id
@Column(name = "CODE")
private String code;
...
// rest of the fields, constructors, getters and setters
}
Object that wraps my list of custom object:
@XmlRootElement(name = "products")
@XmlAccessorType (XmlAccessType.FIELD)
public class RetObjects {
@XmlElement(name = "product")
private List<Product> object = null;
public List<Product> getObject() {
return object;
}
public void setObject(List<Product> object) {
this.object = object;
}
}
MessageBodyReader/Writer
are straight forward just using Jaxb unmarshaller and marshaller over the RetObjects
object.
With this implementation it is working fine as expected and i am able to fetch the RetObjects
wrapping the list of Products perfectly fine at client.
Here my question is, instead of wrapping my List of Products into a intermediate object, RetObjects
in my case, couldn't I marshal and unmarshal List of Products object directly. If I want to write another service that returns List of Orders, I need to wrap this with one more intermediate object. What is the right approach to achieve this? How could I do this without intermediate objects?
>(){}); I am getting compilation error saying readEntity(Class) is not applicable for readEntity(RetObject2
– HJK Dec 25 '14 at 05:14>(){}). Here RetObject2 is a new generic class like RetObject2 with one field of type T. Could you elaborate a bit.