简体   繁体   中英

How to merge two JSON objects?

I have two json objects

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. 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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