Code Monkeyism

Programming is hard by Stephan Schmidt

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.

About the author: Stephan Schmidt is currently a team manager at ImmobilienScout24 in Berlin. Stephan has been working as a head of development and CTO. He has used a lot of different technologies in the last 20 years including Java, Rails and Python. Stephans main field of interest is maintainablity and productivity in software development. Want to know more? All views are only his own.

If you did like this article but you don't want to subscribe to new articles with your reader, you can follow me on Twitter or subscribe to new posts with your email:

Comments

[...] No signal, no noise. « Experiments for nicely generating JSON [...]

Leave a Reply