JSON Builder – Fun with Generics

On the train back to Berlin I spiked a little fluent Json Builder in Java. Here is one of my acceptance tests:

 JsonBuilder builder = new JsonBuilder<NULL>()
            .addProperty("first", "Holden")
            .addProperty("last", "Caulfield")
                .addProperty("street", "5 Mayton St")
        .addProperty("date", "2011-12-12");
JsonObject clientFile =builder.build();

This yields:

    "contact":["00447903217666",{"street":"5 Mayton St"},"004915151183666"],

I am wondering whether people find the nesting of builders with end() useful.
The interesting thing is the type parameter, as there is a JsonBuilder and a JsonArrayBuilder, that can be nested arbitrarily but the end() call always returns the the enclosing type.

The type is recursive ;-).
In JsonBuilder we have:

class JsonBuilder <P> {
    public JsonArrayBuilder<JsonBuilder<P>> addArray(String key); 
    public JsonBuilder<JsonBuilder<P>> addObject(String name);
    public P end();

And in JsonArrayBuilder things are similar:

class JsonArrayBuilder<P>{   
    public JsonBuilder<JsonArrayBuilder<P>> addObject();
    public JsonArrayBuilder<JsonArrayBuilder<P>> addArray();
    public P end();

I was quite surprised, that this thing works. To start with I defined a NULL type for the instance at the root level. Obviously this could be hidden in a static factory method or a subclass.






Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.