Sunday, March 7, 2010

Itemscript a serious JSON library for java

JSON is an interesting alternative to XML. It has originally grown from javaScript but is now widely available for a large number of languages and many libraries are built with JSON support.
Of particular interest is the constant focus of the JSON community on simplicity. The moto seems to be: anything you can do with XML you can do with JSON, faster and cheaper.
itemscript is an example of such a library.
Itemscript is a rich JSON API for java. This is a sample taken from the product test cases that illustrates some of the nice aspects of the API:
JsonArray array = system().createArray()
.a("foo")
.a(1)
.a(1.5)
.a(true)
.a(123L);
assertEquals("foo", array.getString(0));
assertEquals((Integer) 1, array.getInt(1));
assertEquals((Double) 1.5, array.getDouble(2));
assertEquals((Float) 1.5f, array.getFloat(2));
assertEquals((Boolean) true, array.getBoolean(3));
assertEquals((Long) 123L, array.getLong(4));
Notice the elegant chaining of add operations and the automatic type inferencing mechanism.
Itemscipt also has a binding mechanism called the Foundry that ties POJOs to JSON. The best way to illustrate this is to look at some code.
On top of the JSON API, itemscript provides a way to store and query JSON objects in a RESTful manner creating an in-memory database of linked objects. This is an example inspired by the itemscript samples:
/* create a hierarchy */
system.put("mem:/abc/def", "123");
system.put("mem:/abc/ghi", "456");
/* query the in-memory data */
assertEquals(2, (int) system.getInt("mem:/abc?countItems"));
JsonArray keys = system.getArray("mem:/abc?keys");
assertEquals("[\"ghi\",\"def\"]", keys.toCompactJsonString());
JsonArray pagedItems = system.getArray("mem:/abc?pagedItems&numRows=2&startRow=0");
assertEquals("[[\"def\",\"123\"],[\"ghi\",\"456\"]]", pagedItems.toCompactJsonString());
Last but not least, Itemscript is open source and is hosted on Google code.
I am thinking of ways to leverage libraries such as itemscript to provide COBOL to JSON binding. As JSON becomes more and more popular there are good chances its trajectory will cross the legacy applications one. Would be nice to have LegStar at the junction.