It appears to be a little known fact that Java 1.6 includes a JAXB implementation -- no need for external libraries. However, the version that's currently bundled has an annoying bug related to how it packs lists. Let's say that your XML contains a list of items that you'd like to unmarshal and represent internally as a map. One might thing that all you'd have to do is the following:
And what you'll end up with is an empty map. Here's what happened:
- Something.getList() is called and returns null.
- JAXB creates a new ArrayList, and passes it to Something.setList(). At this point there is nothing in the list.
- JAXB unmarshals all of the items, appending them to the list.
I'm sure you see the problem. Fortunately, there is a solution. The latest version of JAXB (available
here) has fixed the problem. It follows the same flow described above, but with one additional step. It calls Something.setList() a second time after populating the list.
Upgrading your version of JAXB is a two step process.
- Put the new jars on your classpath or install them to your Maven repository.
- Prior to unmarshalling, call: System.setProperty("javax.xml.bind.JAXBContext", "com.sun.xml.bind.v2.ContextFactory");
Interesting solution. After rooting around the internet looking for an answer to a very similar problem I was glad to see that you solved it. Very clean.
ReplyDeleteNow if only I can figure out where to put that vodka bottle..