Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

In a previous post, I showed how to use @XmlSeeAlso to inform the JAXB context of inheriting classes. This is great during marshalling. The real pain was on unmarshalling. A requirement we had was that there were two objects that would need to be able to be unmarshalled from the same root element, . This combined with the @XmlSeeAlso caused a problem. When I was unmarshalling an object of A, it consistently returned an object of type B. The only way I found to force it to return a certain object was to specify it via:

        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(...This.class or Super.class...);
            Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
            Source source = new StreamSource(new StringReader(myString));

            JAXBElement<PersonWatchModel> jaxbElement = unmarshaller.unmarshal(source, This.class);
            someClass.setSomeProperty(jaxbElement.getValue());
        } catch (JAXBException e) {
            log.error("JAXBException {}", e);
            throw e;
        }

This forced it to a specific type and I could use the .getValue() property to get the java object that I needed.

September 3rd, 2012

Posted In: Java, JAXB, xml

Leave a Reply

Your email address will not be published. Required fields are marked *

LinkedIn Auto Publish Powered By : XYZScripts.com