Is JAXB for a small amount of POJO?

I am implementing a small RESTful web service and I believe that I will return XML blobs to represent resources that rightly map to some of the Java classes that I have.

I could create my own XML encoders for each class, but I came across JAXB (which I never used) and this seemed like a clean way to avoid having to write tedious coding logic that I would have to sync if I add new properties to any of classes.

So my question is: Is JAXB too heavy for something simple? Is it worth using just something to match the base structure, the beans collection, etc. With an XML document?

edit: I use jersey to create a service.

+6
source share
3 answers

Note. I am an EclipseLink JAXB (MOXy) and a member of the JAXB ( JSR-222 ) expert group.

If you use the JAX-RS implementation ( Jersey , RESTeasy , Wink , etc.) to create a RESTful service, then JAXB is a required default layer and integrates easily:

Example:

+7
source

JAXB also comes β€œfree” with Java 6. If you have control over the XML format (vs must accept an external schema), then JAXB is trivial to use with a little more than a few annotations and very simple sorting code.

A simple toXML method:

JAXBContext ctx = JAXBContext.newInstance(YourClass.class); Marshaller m = ctx.createMarshaller(); m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); StringWriter sw = new StringWriter(); m.marshal(waypointServer, sw); sw.close(); return sw.toString(); 

XML Reader:

  URL url = new URL(filePath); JAXBContext ctx = JAXBContext.newInstance(YourClass.class); Unmarshaller um = ctx.createUnmarshaller(); YourClass yc = (YourClass)um.unmarshal(url.openStream()); 

Simple bean:

 @XmlRootElement public class YourClass { List<Stuff> stuffList; String id; int cnt; // getters, setters } 

It can get more complicated, obviously, but out of the box it can be very simple.

+5
source

I have no opinion on whether JAXB is too "heavy", but if you conclude that it is, and you are looking for an alternative XML serializer, I highly recommend XStream .

It does serialization / deserialization of the real piece of cake, the default behavior makes sense in most cases, and it’s very easy to set up serialization output if you need to.

0
source

Source: https://habr.com/ru/post/893607/


All Articles