简体   繁体   English

如何合并两个JSON对象?

[英]How to merge two JSON objects?

I have two json objects 我有两个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);

This creates two seperate json objects, one for the name and one for the email. 这将创建两个单独的json对象,一个用于名称,另一个用于电子邮件。 I just need one object both with the name and email. 我只需要一个带有名称和电子邮件的对象。 I'm not very well versed in json or javafx so I was trying things like 我不太熟悉json或javafx,所以我正在尝试类似

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

and

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

But neither of these work. 但是这些都不起作用。

Try the following: 请尝试以下操作:

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

Instead of creating two objects, add it to the builder like the code below: 与其创建两个对象,不如将其添加到构建器中,如以下代码所示:

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

And when done building, create the object as below: 构建完成后,如下所示创建对象:

JsonObect taJson = builder.build();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM