Experiments for nicely generating JSON

I’ve been experimenting with ways to nicely generate JSON. There are many ways to generate JSON in Java, like XStream with Jettison, with JAXB or directly with REST API implementation Jersey. Often you don’t want to serialize objects or work mith maps though. Taking code from “The best Markup Builder I could build in Java” I’ve tried a builder approach.

The generated JSON would be

To create nodes for a JSON tree I first tried a node function. But having lots of node calls makes the code quite unreadable. Luckily Java allows $ as a method name. Using $ makes the code much more readable. The List object creates a list of nodes, taking input from a collection, Iterable or Iterator and calling item() for every element.

To reuse generation code one can create semantic methods like an items method:

The nice thing is, with another render mechanism the tree of nodes can also be rendered to XML with a toXml() method, if XML works better for some REST calls. Next thing to add is support for XStream and Jettison to mix serialization in e.g. $("employee", employeePOJO); and experiment on how to make the code even nicer and shorter.

I also wonder how to remove the toJson() call with Jersey and to use a Jersey writer. Any ideas?

Thanks for listening.

How to PUT binary data with REST?

Base64 in XML? Multi-mime? See the question, add a comment if you have an answer, the Google results are not very satisfying. Someone clearly solved the problem. But all REST discussions I’ve found do not adress the problem. Even the “RESTful Web Services” bible is mostly silent on the topic (And I don’t want to declare the binary object a resource and PUT binary data into it).

Adding Web Beans JSR 299 to Jersey for REST

While playing with Web Beans I thought it would be nice to add Web Beans support to Jersey. Jersey is a JSR 311 implementation for RESTful web services in Java. Though it has taken some flak, I – and others – think it’s easy to use. Because it’s easy in Jersey to control the creation of objects by writing your own servlet with a Jersey ComponentProvider, I finished a quick hack in no time. Some help was the integration examples for Spring.

Having defined this servlet, a REST resource example for the UuidService from my last post about Web Beans, looks like this

Works like a charm. The UUIDService is injected through Web Beans and the scopes from Web Beans, @RequestScope and @SessionScope seem to work. This takes a big burden from the developer.

I hope to implement a SOFEA web application with Javascript parts which communicate with the backend via REST. For performance reasons it would be nice to populate and render the Javascript on the server. Therefore I would wish I could resolve REST calls to Jersey internally like

to pre-populate pages with REST calls in them.

Thanks for listening.

Update:The Jersey lead wrote about a Jersey client API which perhaps does what I want. Splendid.