0

I need to make a Builder class in which I need to have below fields so when I populate those fields in my Builder class and then if I call toJson method on it which I need to create as well, then it should make json structure like as shown below:

{
    "id": "hello",
    "type": "process",
    "makers": {
        "typesAndCount": {
            "abc": 4,
            "def": 3,
            "pqr": 2
        }
    }
}

Key in my above JSON is fixed always only the values will change. But in typesAndCount field I have three different keys abc, def and pqr. Sometimes I will have one key there or two keys or all the keys. So stuff in typesAndCount key can change depending on what's being passed. Below is also possible case.

{
    "id": "hello",
    "type": "process",
    "makers": {
        "typesAndCount": {
            "abc": 4,
            "def": 3,
        }
    }
}

I started with below code in my Builder class but not sure how should I proceed further.

public class Key {

    private final String id;
    private final String type;

    // confuse now

}

I just want to populate data in my class and then call some method it can be toJson to make string in above JSON format.

user1950349
  • 4,738
  • 19
  • 67
  • 119

1 Answers1

3

User Builder pattern for fluent configure your data builder. E.g.

class Builder {

private final String id;
private final String type;

private Map<String, Integer> map = new HashMap<>();

// mandatory fields are always passed through constructor 
Builder(String id, String type) {
    this.id = id;
    this.type = type;
}

Builder typeAndCount(String type, int count) {
    map.put(type, count);
    return this;
}

JsonObject toJson() {

    JsonObjectBuilder internal = null;
    if (!map.isEmpty()) {
        internal = Json.createObjectBuilder();
        for (Map.Entry<String, Integer> e: map.entrySet()) {
            internal.add(e.getKey(), e.getValue());
        }
    }
    // mandatory fields
    JsonObjectBuilder ob = Json.createObjectBuilder()
            .add("id", id)
            .add("type", type);

    if (internal != null) {
        ob.add("makers", Json.createObjectBuilder().add("typesAndCount", internal));
    }
    return ob.build();
}

public static void main(String[] args) {
    Builder b = new Builder("id_value", "type_value")
            .typeAndCount("abs", 1)
            .typeAndCount("rty", 2);

    String result = b.toJson().toString();
    System.out.println(result);
}
}

As you can see you can call typeAndCount as many times as you need or even don't call it at all. toJson method handles this without any problem.

UPDATE: The output for example in method main is

{"id":"id_value","type":"type_value","makers":{"typesAndCount":{"abs":1,"rty":2}}}

UPDATE 2: the builder without 'typeAndCount` method call at all will produce this output

{"id":"id_value","type":"type_value"}

Andriy Kryvtsun
  • 3,220
  • 3
  • 27
  • 41
  • Thanks for an example. Now do you have any idea how can I create a JSON structure in my `toJson` method? – user1950349 Feb 29 '16 at 20:51
  • which json library are you using? I am not able to find `JsonObjectBuilder` and `Json` classes? I am mainly familiar with Gson or Jackson. – user1950349 Feb 29 '16 at 20:53
  • @user1950349 I used `Running` maven dependency from [this page](https://jsonp.java.net/download.html) – Andriy Kryvtsun Feb 29 '16 at 21:01
  • got it. it works fine but in my library I am only using jackson so for this I need to add another extra dependency which I am trying to avoid. Is there any way we can accomplish same thing using jackson? – user1950349 Feb 29 '16 at 21:05
  • @user1950349 unfortunately, Jackson uses another [more complex scheme](http://stackoverflow.com/questions/16974474/creating-a-json-object-using-jackson) for JSON creation – Andriy Kryvtsun Feb 29 '16 at 21:24
  • @user1950349 if you can use Gson it's ease to rework my `toJson` method with `GsonBuilder`. See [this example](http://www.javacreed.com/simple-gson-example/) – Andriy Kryvtsun Feb 29 '16 at 21:28