Archive for the ‘XML’ Category

In a recent project I was facing the problem that a JSON interface had to be added to an already existing XML interface. The XML was rendered using JSPs. That’s fine and I didn’t want to change that. I also didn’t want to duplicate the JSPs by writing additional JSPs that generate JSON. The easiest solution that came into my mind was to add a simple servlet filter that converts the generated XML to JSON on the fly when JSON format is requested.

In our web application the desired format (XML or JSON) was added as a request parameter to the HTTP request). All the servlet filter has to do is to check this parameter to decide whether the XML should be converted to JSON.

In order to compile and use the code you also need the following libraries:

The JsonResponseWrapper does the XML to JSON conversion. Please note that this implementation buffers the complete XML in memory. This approach is not appropriate for very large XML, but it was working very well for our application:

The code was pretty straight forward to write. But maybe it is still helpful for someone who has a similar problem. It can be optimized to use a streaming approach versus the in memory buffering of the XML. But that wasn’t needed for my purposes, so I leave this up to you. ;-)

XStream is a Java xml library, which nicely serializes Java objects to XML and vice versa. It can easily deal with missing (i.e. optional) XML elements. The corresponding Java fields will just be left blank.

In this case the optional <role> field is missing in the XML and the corresponding field in the User Java object will be left null when deserializing the XML.

But once if you have decided on your XML API, you might want to question if it is flexible enough. Just consider you have built software based on this XML spec. Can you still add optional XML elements without breaking the applications that you have already shipped? Consider you want to add more information, like a <department> element. Will your clients be able to just ignore this piece of information? The short answer is: No. XStream will throw a ConversionException if it finds an element that has no corresponding Java field. The Jira ticket XSTR-30 is an improvement request related to this topic. But so far XStream has no simple switch to turn off complaining about unknown elements.

But you could easily tweak XStream to ignore additional elements by adding your own custom mapper that ignores the field. The following snippet creates an XStream instance that ignores additional fields. It is grabbed from the CustomMapperTest.testCanBeUsedToOmitUnexpectedElements() unit test that is part of the XStream source code: