ripper234 ripper234 - 1 month ago 26
Java Question

How to fluently build JSON in Java?

I'm thinking of something like:

String json = new JsonBuilder()
.add("key1", "value1")
.add("key2", "value2")
.add("key3", new JsonBuilder()
.add("innerKey1", "value3"))
.toJson();


Which Java JSON library is best for this kind of fluent building?

Update: I wrapped GSON and got almost the desired result ... with one hitch.

Answer

I am using http://www.json.org/javadoc/org/json/JSONObject.html and found a nice and friendly json lib.

Example:

String jsonString = new JSONObject()
                  .put("JSON1", "Hello World!")
                  .put("JSON2", "Hello my World!")
                  .put("JSON3", new JSONObject()
                       .put("key1", "value1")).toString();

System.out.println(jsonString);

OUTPUT:

{"JSON2":"Hello my World!","JSON3":{"key1":"value1"},"JSON1":"Hello World!"}