I’m using JAX-RS Jersey and JAXB on my server code to implement services. I am sending xml as input to resource and in the resource i am converting xml to object using JAXBContext. My resource is working when the xml consist of one root element.
like
<employee>
<id>1</id>
</employee>
But when i provide multiple elements I am getting UnmarshalException.
<employee>
<id>1</id>
</employee>
<employee>
<id>2</id>
</employee>
My resource look like this.
@POST
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_XML)
public Response addEmp(@Context HttpServletRequest req)throws JAXBException,IOException{
JAXBContext jaxb = JAXBContext.newInstance(Employee.class);
Employee emps = (Employee)jaxb.createUnmarshaller().unmarshal(req.getInputStream());
emplist.add(emps);
return Response.ok().entity(success).build();
First of all, don’t use
req.getInputStream(). Instead, specify your input stream as an argument of a function:Second, your input XML is not a valid document. XML has to have a root element. You can’t give a few elements in one input stream. Instead, use a JAXB wrapper.