Search code examples
javajsonxmljaxbpojo

Converting JSON to POJO using JAXB


I´m using ElasticSearch to store some data related to events that are happening with objects, a Track and Trace Model. To do that I used JAXB to generate de model classes using a XSD file. I can save the data on ES easily transforming the Data data comes in XML to POJO and after that to JSON. The problem that I´m having is to get the data back. I´m trying to use the same logic JSON to POJO (using JAXB) and POJO to XML on the web service. Like that:

JAXBContext jc = JAXBContext.newInstance(EPCISDocumentType.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
unmarshaller.setProperty("eclipselink.media-type", "application/json");
unmarshaller.setProperty("eclipselink.json.include-root", true);
String eventJSON = elasticEvent.getSpecific("event", "raw", eventID);

The String comes with the expected event but when I try to transform to POJO the object comes only with the outer most class (EPCISDocumentType) but with 0 contents. I´m trying like that:

StreamSource eventStream = new StreamSource(new StringReader(eventJSON));
EPCISDocumentType foundEvent =  unmarshaller.unmarshal(eventStream,EPCISDocumentType.class).getValue();

The problem is why this is happening, I´m using exactly the same libraries to do Marshal but I can´t unmarshal it back to the same content.


Solution

  • I use ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper) for both marshaling and unmarshaling. It's much easier to use. See bellow:

    ObjectMapper mapper = new ObjectMapper();
    //Get the json as String
    String objectAsJsonString= mapper.writeValueAsString(foundEvent);
    //Create the object from the String 
    EPCISDocumentType foundEvent = mapper.readValue(objectAsJsonString,EPCISDocumentType.class);
    

    When you have lists of objects you want to marshal/unmarshal, it works only if you put the list in a wrapper.

    Also jackson is more performant than jaxb. Check these tests: http://tuhrig.de/jaxb-vs-gson-and-jackson/