填充构建器 class 然后从中创建一个 json 字符串

populate builder class and then make a json string out of it

我需要制作一个 Builder class,其中我需要有以下字段,所以当我在我的 Builder class 中填充这些字段时,然后如果我调用 toJson 方法我也需要创建它,然后它应该使 json 结构如下所示:

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

我上面的键 JSON 始终是固定的,只有值会改变。但是在 typesAndCount 字段中,我有三个不同的键 abcdefpqr。有时我会有一把钥匙或两把钥匙或所有钥匙。所以 typesAndCount 键中的内容可以根据传递的内容而改变。以下也是可能的情况。

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

我在我的构建器中使用以下代码开始 class 但不确定我应该如何进一步进行。

public class Key {

    private final String id;
    private final String type;

    // confuse now

}

我只想在我的 class 中填充数据,然后调用一些方法 toJson 来制作上述 JSON 格式的字符串。

用于流畅配置数据生成器的用户生成器模式。例如

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);
}
}

如您所见,您可以根据需要多次调用 typeAndCount,甚至根本不调用它。 toJson 方法可以毫无问题地处理这个问题。

更新: 例如方法 main 中的输出是

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

更新 2: 完全不调用“typeAndCount”方法的构建器将产生此输出

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