Converting JSON to XML

I have been working on a validation tool that would allow us to validate JSON messages. I could not any usable JSON validator in Java so I have decided to use RelaxNG. It had one catch. RelaxNG is designed for XML validation, not JSON.

That's the reason why I have decided to convert JSON to XML. Before we dive into the implementation, let's think about the problem in general. Both JSON and XML ale tree structures and they are quite similar. In fact, I have discovered only the following differences.

  1. JSON supports multiple top-level elements. In XML we can have only one root element. While {"a":1, "b":2} is a valid JSON document, <a>1</a><b>2</b> is not valid XML.
  2. JSON supports arrays, XML does not.
  3. JSON has null keyword, in XML we several options how to deal with nulls. We can either represent it by an empty element or using xsi:nil attribute.
  4. JSON has support for boolean and numeric types. In JSON {"a":1} has different meaning than {"a":"1"} (with double quotes). It's not possible to represent such difference in the XML.

All of the problems were acceptable for my needs. There would be more problems when going in the other direction, from XML to JSON, but I did not need it. The only thing I have needed was to convert from

{"root":{
	"data1":[
		[1,2,3], 				
        	[4,5,6]
	],
	"data2":null,
	"data3":"2011-05-30T10:00:00",
	"data4":
	{
		"a":1,
     		"b":2
	}
}
}

to

<?xml version="1.0" encoding="UTF-8"?>
<root>
	<data1>
		<data1>
			<data1>1</data1>
			<data1>2</data1>
			<data1>3</data1>
		</data1>
		<data1>
			<data1>4</data1>
			<data1>5</data1>
			<data1>6</data1>
		</data1>
	</data1>
	<data2/>
	<data3>2011-05-30T10:00:00</data3>
	<data4>
		<a>1</a>
		<b>2</b>
	</data4>
</root>  

There already is a project Jettison, that is able to convert between JSON and XML but it does not handle JSON arrays properly. Moreover, I have encountered some bugs like this one. It's trivial to fix but it's there for more than half a year. Strange.

One nice Saturday morning I have decided to implement it. And I have found that it's incredibly easy. It's just matter of using Jackson pull parser and generating SAX events based on it. It's about 200 lines of code that you can enjoy here here.

Tags: ,

Comments are closed.