Category Archives: Articles in English

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.

Using Jing for Relax NG validation

I just ant to jot down how to programmatically use Jing for Relax NG validation. It has a simple API but I could not find any description besides the JavaDoc. It took me some time to figure out how to use it.

If you want to validate a XML file, just use ValidationDriver. If you have a DOM Document or StAX source, just do the following

//we are using Relax NG compact format
SchemaReader schemaReader = CompactSchemaReader.getInstance();

//schema can be reused, it's thread safe
Schema schema = schemaReader.createSchema(ValidationDriver.fileInputSource(new File("your_schema.txt)), PropertyMap.EMPTY);

//can use different error handler here (try DraconianErrorHandler http://www.thaiopensource.com/relaxng/api/jing/com/thaiopensource/xml/sax/DraconianErrorHandler.html)
ErrorHandler seh = new ErrorHandlerImpl();
PropertyMapBuilder  builder = new PropertyMapBuilder();
builder.put(ValidateProperty.ERROR_HANDLER, seh);
		
//Validator is NOT thread safe
Validator validator = schema.createValidator(builder.toPropertyMap());
			
		
Source source = ...//your XML source

TransformerFactory.newInstance().newTransformer().transform(source, new SAXResult(validator.getContentHandler()));

And that’s it.

Visualizing Fork/Join

Last Friday I have participated on GPars Hackathon. Together with Jety we have picked the task “Catchy visual demos“. Neither of us had used Swing for several years and we are newbies in both Groovy and GPars. But Václav helped us to solve several Groovy mean tricks and at the end we managed to create really nice demo. It’s a visualization of Fork/Join based merge-sort. You can enjoy it here. You can really see how fork/join aka jsr166y works. Cool.

THE DEMO (alternatively you can download and execute this jar)

The source code can be downloaded here although it’s much less enjoyable than the application itself. I have to confess that I enjoyed it so much that I have rewritten it to Java and in fact that’s what you are really looking at. In Java it’s less elegant, but you do not have to download 5Mb of Groovy libraries. I also hoped that in Java it would run in sandbox without special permissions. Unfortunately you are not allowed to manipulate with threads in and untrusted app, so you have to trust my self-signed certificate. The Java source is available on GitHub.