144
votes

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.

4
  • 1
    I don't think I've seen any JSON library that follows that style. Perhaps you could extend an existing library to do what you want?
    – aroth
    Jan 16, 2012 at 5:36
  • 1
    @aroth - I'm writing a wrapper around com.google.gson as we speak.
    – ripper234
    Jan 16, 2012 at 5:38
  • 1
    Almost ready - stackoverflow.com/questions/8876271/…
    – ripper234
    Jan 16, 2012 at 6:00
  • 1
    Construct the appropriate "nest" of Maps and Lists and serialize it. Avoid "long chain polymer" statements.
    – Hot Licks
    Jan 8, 2015 at 17:03

12 Answers 12

199
votes

I am using the org.json library and found it to be nice and friendly.

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!"}
4
  • 21
    This is not much fluent.
    – Vlad
    Oct 4, 2014 at 1:49
  • The web you provided doesn't work anymore. Would you mind updating it? Dec 3, 2016 at 22:12
  • 14
    @Vlad - this is exactly what fluent builders suggest to me. Can you provide an example of a setup that you would think is better?
    – scubbo
    Apr 4, 2018 at 17:18
  • 20
    This is still the cleaner option. It's ridiculous that Java devs still have to pause to figure the best option for JSON parse/build in 2020.
    – mtyson
    Dec 23, 2019 at 20:11
128
votes

See the Java EE 7 Json specification. This is the right way:

String json = Json.createObjectBuilder()
            .add("key1", "value1")
            .add("key2", "value2")
            .build()
            .toString();
5
11
votes

I recently created a library for creating Gson objects fluently:

http://jglue.org/fluent-json/

It works like this:

  JsonObject jsonObject = JsonBuilderFactory.buildObject() //Create a new builder for an object
  .addNull("nullKey")                            //1. Add a null to the object

  .add("stringKey", "Hello")                     //2. Add a string to the object
  .add("stringNullKey", (String) null)           //3. Add a null string to the object

  .add("numberKey", 2)                           //4. Add a number to the object
  .add("numberNullKey", (Float) null)            //5. Add a null number to the object

  .add("booleanKey", true)                       //6. Add a boolean to the object
  .add("booleanNullKey", (Boolean) null)         //7. Add a null boolean to the object

  .add("characterKey", 'c')                      //8. Add a character to the object
  .add("characterNullKey", (Character) null)     //9. Add a null character to the object

  .addObject("objKey")                           //10. Add a nested object
    .add("nestedPropertyKey", 4)                 //11. Add a nested property to the nested object
    .end()                                       //12. End nested object and return to the parent builder

  .addArray("arrayKey")                          //13. Add an array to the object
    .addObject()                                 //14. Add a nested object to the array
      .end()                                     //15. End the nested object
    .add("arrayElement")                         //16. Add a string to the array
    .end()                                       //17. End the array

    .getJson();                                  //Get the JsonObject

String json = jsonObject.toString();

And through the magic of generics it generates compile errors if you try to add an element to an array with a property key or an element to an object without a property name:

JsonObject jsonArray = JsonBuilderFactory.buildArray().addObject().end().add("foo", "bar").getJson(); //Error: tried to add a string with property key to array.
JsonObject jsonObject = JsonBuilderFactory.buildObject().addArray().end().add("foo").getJson(); //Error: tried to add a string without property key to an object.
JsonArray jsonArray = JsonBuilderFactory.buildObject().addArray("foo").getJson(); //Error: tried to assign an object to an array.
JsonObject jsonObject = JsonBuilderFactory.buildArray().addObject().getJson(); //Error: tried to assign an object to an array.

Lastly there is mapping support in the API which allows you to map your domain objects to JSON. The goal being when Java8 is released you'll be able to do something like this:

Collection<User> users = ...;
JsonArray jsonArray = JsonBuilderFactory.buildArray(users, { u-> buildObject()
                                                                 .add("userName", u.getName())
                                                                 .add("ageInYears", u.getAge()) })
                                                                 .getJson();
9
votes

If you are using Jackson do a lot of JsonNode building in code, you may be interesting in the following set of utilities. The benefit of using them is that they support a more natural chaining style that better shows the structure of the JSON under construction.

Here is an example usage:

import static JsonNodeBuilders.array;
import static JsonNodeBuilders.object;

...

val request = object("x", "1").with("y", array(object("z", "2"))).end();

Which is equivalent to the following JSON:

{"x":"1", "y": [{"z": "2"}]}

Here are the classes:

import static lombok.AccessLevel.PRIVATE;

import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.JsonNodeFactory;
import com.fasterxml.jackson.databind.node.ObjectNode;

import lombok.NoArgsConstructor;
import lombok.NonNull;
import lombok.RequiredArgsConstructor;
import lombok.val;

/**
 * Convenience {@link JsonNode} builder.
 */
@NoArgsConstructor(access = PRIVATE)
public final class JsonNodeBuilders {

  /**
   * Factory methods for an {@link ObjectNode} builder.
   */

  public static ObjectNodeBuilder object() {
    return object(JsonNodeFactory.instance);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, boolean v1) {
    return object().with(k1, v1);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, int v1) {
    return object().with(k1, v1);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, float v1) {
    return object().with(k1, v1);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, String v1) {
    return object().with(k1, v1);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, String v1, @NonNull String k2, String v2) {
    return object(k1, v1).with(k2, v2);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, String v1, @NonNull String k2, String v2,
      @NonNull String k3, String v3) {
    return object(k1, v1, k2, v2).with(k3, v3);
  }

  public static ObjectNodeBuilder object(@NonNull String k1, JsonNodeBuilder<?> builder) {
    return object().with(k1, builder);
  }

  public static ObjectNodeBuilder object(JsonNodeFactory factory) {
    return new ObjectNodeBuilder(factory);
  }

  /**
   * Factory methods for an {@link ArrayNode} builder.
   */

  public static ArrayNodeBuilder array() {
    return array(JsonNodeFactory.instance);
  }

  public static ArrayNodeBuilder array(@NonNull boolean... values) {
    return array().with(values);
  }

  public static ArrayNodeBuilder array(@NonNull int... values) {
    return array().with(values);
  }

  public static ArrayNodeBuilder array(@NonNull String... values) {
    return array().with(values);
  }

  public static ArrayNodeBuilder array(@NonNull JsonNodeBuilder<?>... builders) {
    return array().with(builders);
  }

  public static ArrayNodeBuilder array(JsonNodeFactory factory) {
    return new ArrayNodeBuilder(factory);
  }

  public interface JsonNodeBuilder<T extends JsonNode> {

    /**
     * Construct and return the {@link JsonNode} instance.
     */
    T end();

  }

  @RequiredArgsConstructor
  private static abstract class AbstractNodeBuilder<T extends JsonNode> implements JsonNodeBuilder<T> {

    /**
     * The source of values.
     */
    @NonNull
    protected final JsonNodeFactory factory;

    /**
     * The value under construction.
     */
    @NonNull
    protected final T node;

    /**
     * Returns a valid JSON string, so long as {@code POJONode}s not used.
     */
    @Override
    public String toString() {
      return node.toString();
    }

  }

  public final static class ObjectNodeBuilder extends AbstractNodeBuilder<ObjectNode> {

    private ObjectNodeBuilder(JsonNodeFactory factory) {
      super(factory, factory.objectNode());
    }

    public ObjectNodeBuilder withNull(@NonNull String field) {
      return with(field, factory.nullNode());
    }

    public ObjectNodeBuilder with(@NonNull String field, int value) {
      return with(field, factory.numberNode(value));
    }

    public ObjectNodeBuilder with(@NonNull String field, float value) {
      return with(field, factory.numberNode(value));
    }

    public ObjectNodeBuilder with(@NonNull String field, boolean value) {
      return with(field, factory.booleanNode(value));
    }

    public ObjectNodeBuilder with(@NonNull String field, String value) {
      return with(field, factory.textNode(value));
    }

    public ObjectNodeBuilder with(@NonNull String field, JsonNode value) {
      node.set(field, value);
      return this;
    }

    public ObjectNodeBuilder with(@NonNull String field, @NonNull JsonNodeBuilder<?> builder) {
      return with(field, builder.end());
    }

    public ObjectNodeBuilder withPOJO(@NonNull String field, @NonNull Object pojo) {
      return with(field, factory.pojoNode(pojo));
    }

    @Override
    public ObjectNode end() {
      return node;
    }

  }

  public final static class ArrayNodeBuilder extends AbstractNodeBuilder<ArrayNode> {

    private ArrayNodeBuilder(JsonNodeFactory factory) {
      super(factory, factory.arrayNode());
    }

    public ArrayNodeBuilder with(boolean value) {
      node.add(value);
      return this;
    }

    public ArrayNodeBuilder with(@NonNull boolean... values) {
      for (val value : values)
        with(value);
      return this;
    }

    public ArrayNodeBuilder with(int value) {
      node.add(value);
      return this;
    }

    public ArrayNodeBuilder with(@NonNull int... values) {
      for (val value : values)
        with(value);
      return this;
    }

    public ArrayNodeBuilder with(float value) {
      node.add(value);
      return this;
    }

    public ArrayNodeBuilder with(String value) {
      node.add(value);
      return this;
    }

    public ArrayNodeBuilder with(@NonNull String... values) {
      for (val value : values)
        with(value);
      return this;
    }

    public ArrayNodeBuilder with(@NonNull Iterable<String> values) {
      for (val value : values)
        with(value);
      return this;
    }

    public ArrayNodeBuilder with(JsonNode value) {
      node.add(value);
      return this;
    }

    public ArrayNodeBuilder with(@NonNull JsonNode... values) {
      for (val value : values)
        with(value);
      return this;
    }

    public ArrayNodeBuilder with(JsonNodeBuilder<?> value) {
      return with(value.end());
    }

    public ArrayNodeBuilder with(@NonNull JsonNodeBuilder<?>... builders) {
      for (val builder : builders)
        with(builder);
      return this;
    }

    @Override
    public ArrayNode end() {
      return node;
    }

  }

}

Note that the implementation uses Lombok, but you can easily desugar it to fill in the Java boilerplate.

2
votes
String json = new JsonBuilder(new GsonAdapter())
  .object("key1", "value1")
  .object("key2", "value2")
  .object("key3")
    .object("innerKey1", "value3")
    .build().toString();

If you think the above solution is elegant, then please try out my JsonBuilder lib. It was created to allow one way of building json structures for many types of Json libraries. Current implementations include Gson, Jackson and MongoDB. For ie. Jackson just swap:

String json = new JsonBuilder(new JacksonAdapter()).

I'll happily add others on request, it`s also quite easy to implement one by oneself.

1
1
vote

It sounds like you probably want to get ahold of json-lib:

http://json-lib.sourceforge.net/

Douglas Crockford is the guy who invented JSON; his Java library is here:

http://www.json.org/java/

It sounds like the folks at json-lib picked up where Crockford left off. Both fully support JSON, both use (compatible, as far as I can tell) JSONObject, JSONArray and JSONFunction constructs.

'Hope that helps ..

2
  • Does it support fluent syntax?
    – ripper234
    Jan 16, 2012 at 5:37
  • dead link for me
    – john k
    Mar 2, 2022 at 19:18
1
vote

The reference implementation includes a fluent interface. Check out JSONWriter and its toString-implementing subclass JSONStringer

0
votes

I got here looking for a nice way to write rest endpoint tests with a fluent json builder. In my case I used JSONObject to construct a specialized builder. It need a bit of instrumentation, but the usage is really nice:

import lombok.SneakyThrows;
import org.json.JSONObject;

public class MemberJson extends JSONObject {

    @SneakyThrows
    public static MemberJson builder() {
        return new MemberJson();
    }

    @SneakyThrows
    public MemberJson name(String name) {
        put("name", name);
        return this;
    }

}
MemberJson.builder().name("Member").toString();
0
votes

I am using org.json to create json on demand. My ask was, I had a basic json object, but before sending it to my API I need to wrap it in one wrapper element.

Below is the code done to generate this json for Functional Tests.

Suppose below is the content of base-request.json file

{
  "name":"sanjay"
  "age":32,
  "occupation":"software engineer"
}


String baseRequest = Files.readString(Paths.get("./src/test/resources", "base-request.json"));
    JSONObject baseJsonObject = new JSONObject(baseRequest);
    JSONObject wrappedJsonObject = new JSONObject().put("employee", baseJsonObject);

And now the wrappedJsonObject is sent to my API which expects the request in the form of

{
  "employee": {
    "name":"sanjay"
    "age":32,
    "occupation":"software engineer"
  }
}

Below is the test code, with RestAssured API to pass the Json to my API

RequestSpecification request = given()
            .contentType(JSON)
            .body(wrappedJsonObject.toString());
    response = request.post(new URL(HTTP, host, port, endPoint));
-1
votes

it's much easier than you think to write your own, just use an interface for JsonElementInterface with a method string toJson(), and an abstract class AbstractJsonElement implementing that interface,

then all you have to do is have a class for JSONProperty that implements the interface, and JSONValue(any token), JSONArray ([...]), and JSONObject ({...}) that extend the abstract class

JSONObject has a list of JSONProperty's
JSONArray has a list of AbstractJsonElement's

your add function in each should take a vararg list of that type, and return this

now if you don't like something you can just tweak it

the benifit of the inteface and the abstract class is that JSONArray can't accept properties, but JSONProperty can accept objects or arrays

-1
votes

Underscore-java library has json builder.

import com.github.underscore.U;

public static void main(String[] args) {
  String json = U.objectBuilder()
    .add("key1", "value1")
    .add("key2", "value2")
    .add("key3", U.objectBuilder()
      .add("innerKey1", "value3"))
    .toJson();
  System.out.println(json);
}

Output:
{
  "key1": "value1",
  "key2": "value2",
  "key3": {
    "innerKey1": "value3"
  }
}
-2
votes

You can use one of Java template engines. I love this method because you are separating your logic from the view.

Java 8+:

<dependency>
  <groupId>com.github.spullara.mustache.java</groupId>
  <artifactId>compiler</artifactId>
  <version>0.9.6</version>
</dependency>

Java 6/7:

<dependency>
  <groupId>com.github.spullara.mustache.java</groupId>
  <artifactId>compiler</artifactId>
  <version>0.8.18</version>
</dependency>

Example template file:

{{#items}}
Name: {{name}}
Price: {{price}}
  {{#features}}
  Feature: {{description}}
  {{/features}}
{{/items}}

Might be powered by some backing code:

public class Context {
  List<Item> items() {
    return Arrays.asList(
      new Item("Item 1", "$19.99", Arrays.asList(new Feature("New!"), new Feature("Awesome!"))),
      new Item("Item 2", "$29.99", Arrays.asList(new Feature("Old."), new Feature("Ugly.")))
    );
  }

  static class Item {
    Item(String name, String price, List<Feature> features) {
      this.name = name;
      this.price = price;
      this.features = features;
    }
    String name, price;
    List<Feature> features;
  }

  static class Feature {
    Feature(String description) {
       this.description = description;
    }
    String description;
  }
}

And would result in:

Name: Item 1
Price: $19.99
  Feature: New!
  Feature: Awesome!
Name: Item 2
Price: $29.99
  Feature: Old.
  Feature: Ugly.

Not the answer you're looking for? Browse other questions tagged or ask your own question.