Question

In my webservice (using RestEasy) project I have a dependency to a jar. I use from that jar a java class : Person.

My problem is that I need to serialize a Person instance to XML, But I get the following error :

unable to marshal type "entities.Person" as an element because it is missing an @XmlRootElement annotation

However, I cannot change the Person class to add the annotation @XmlRootElement (it is a third party jar).

Is there any other way (methods, libraries, ... ) to marshal a Person instance into XML without annotating Person class?

BTW, here it is the code I use, but it fails because of the missing annotation :

String result;
Person person = personManager.findByPersonId(personId);
StringWriter sw = new StringWriter();
JAXBContext personContext = JAXBContext.newInstance(Person.class);
Marshaller personMarshaller = personContext.createMarshaller();
personMarshaller.marshal(person, sw);
result = sw.toString();
return Response.status(200).entity(result).build();

Thank you a lot.

Was it helpful?

Solution

JAXB (JSR-222) implementations do not require any annotations be added to your domain model. In the absence of an @XmlRootElement (or @XmlElementDecl) you simply need to wrap your root object in an instance of JAXBElement.

JAXBElement<Person> jaxbElement = new JAXBElement<Person>(new QName("person"), Person.class, person);
personMarshaller.marshal(jaxbElement, sw);

For More Information


Note: I'm the EclipseLink JAXB (MOXy) lead and a member of the JAXB (JSR-222) expert group.

If you need to provide metadata for your model, but don't have access to the source then MOXy offers an external metadata document extension you can use for this purpose.

Thank you, the link you gave me is useful, but I wonder if this EclipseLink library is safe to integrate in a commercial product (license)...

MOXy has been the default JAXB implementation in WebLogic since version 12.1.1, so it's definitely enterprise ready.

EclipseLink (and MOXy) is dual licensed under the Eclipse Public License and Eclipse Distribution License (BSD):

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top