如何合并两个JSON对象?

时间:2017-02-22 15:23:46

标签: java json

我有两个json对象

JsonObject taJson = Json.createObjectBuilder()
            .add(JSON_NAME, ta.getName()).build();
JsonObject taJsontwo = Json.createObjectBuilder()
            .add(JSON_EMAIL, ta.getEmail()).build();
array.add(taJson);
array.add(taJsontwo);

这将创建两个单独的json对象,一个用于名称,另一个用于电子邮件。我只需要一个带有名称和电子邮件的对象。我对json或javafx不太熟悉,所以我在尝试像

这样的东西
JsonObject taJson = Json.createObjectBuilder()
                .add(JSON_NAME, ta.getName()).build();
taJson.add(JSON_EMAIL, ta.getEmail()).build();

JsonObject taJson = Json.createObjectBuilder()
                .add(JSON_NAME, ta.getName()).build();
JsonObject taJson = Json.createObjectBuilder()
                .add(JSON_EMAIL, ta.getEmail()).build();

但这些都不奏效。

2 个答案:

答案 0 :(得分:0)

尝试以下方法:

JsonObject taJson = Json.createObjectBuilder()
            .add(JSON_NAME, ta.getName()).build();
JsonObject taJsontwo = Json.createObjectBuilder()
            .add(JSON_EMAIL, ta.getEmail()).build();
JSONObject combined = new JSONObject();
combined.put("name", taJson);
combined.put("email", taJsontwo);

答案 1 :(得分:0)

不是创建两个对象,而是将它添加到构建器中,如下面的代码所示:

JsonObjectBuilder builder = Json.createObjectBuilder().add(JSON_NAME, ta.getName());
builder.add(JSON_EMAIL, ta.getEmail());

完成构建后,按如下所示创建对象:

JsonObect taJson = builder.build();
相关问题