填充构建器类,然后从中生成一个json字符串

时间:2016-02-29 20:12:58

标签: java json jackson builder

我需要创建一个Builder类,我需要在其中包含以下字段,所以当我在Builder类中填充这些字段然后如果我在其上调用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,
        }
    }
}

我从Builder类的下面的代码开始,但不确定如何继续进行。

public class Key {

    private final String id;
    private final String type;

    // confuse now

}

我只是想在我的类中填充数据,然后调用一些方法,它可以toJson以上面的JSON格式生成字符串。

1 个答案:

答案 0 :(得分:3)

用于构建数据构建器的用户构建器模式。 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);
}
}

如您所见,您可以根据需要多次拨打typeAndCount,甚至根本不打电话给toJsonmain方法可以毫无问题地处理此问题。

更新:方法{{1}}中的输出

  

{&#34; ID&#34;:&#34; ID_VALUE&#34;&#34;类型&#34;:&#34; type_value&#34;&#34;制造商&#34;:{ &#34; typesAndCount&#34; {&#34; ABS&#34;:1,&#34; RTY&#34;:2}}}

更新2:没有&#39; typeAndCount`方法调用的构建器将产生此输出

  

{&#34; id&#34;:&#34; id_value&#34;,&#34; type&#34;:&#34; type_value&#34;}