ripper234 ripper234 - 11 months ago 87
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"))

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 Source

I am using and found a nice and friendly json lib.


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



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