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.

@GET
@ProduceMime("application/json")
public String getList() {
  ShoppingList list = service.getList("123");

  return toJson(
    $("items", 
      new List<ShoppingItem>(list) {
        protected Node item(ShoppingItem shoppingItem) {
          return $("description", shoppingItem.getDescription());
        }
    })
  );
}

The generated JSON would be

{ items: [ { description: "Apple"}, { description: "Orange"} ]}

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:

  public static Node items(Node... nodes) {
    return $("items", nodes);
  }

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.

Stephan Schmidt Administrator
CTO Coach , svese
Stephan is a CTO coach. He has been a coder since the early 80s, has founded several startups and worked in small and large companies as CTO. After he sold his latest startup he took up CTO coaching. He can be found on LinkedIn or follow him in Twitter.
follow me