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.

If you liked this post, subscribe to my free full RSS feed.
Filed under: Java, Javascript, Jersey, REST

You can share this post!
Do you want to tell others about this article? Use the social bookmark icons to submit this artice to the service of your choice. Thanks.

Get free updates by email

If you did like this article you can get free updates with your RSS reader, you can follow me on Twitter or get free update to new posts by email. Enter your email:

 
About the author: Stephan has been working as a head of development and CTO. He has experiences in different technologies since 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.

Comments

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

Leave a Reply