adam bien's blog

How to merge javax.json.JsonObject instances 📎

Combining multiple javax.json.JsonObject instances requires copying their contents into a single JsonObjectBuilder instance:

@Test
public void merge() {
	JsonObject dev = Json.createObjectBuilder().
			add("developer", "duke").
			build();
	JsonObject lang = Json.createObjectBuilder().
			add("language", "java").
			build();

	JsonObjectBuilder result = Json.createObjectBuilder();
	dev.entrySet().forEach(s -> result.add(s.getKey(), s.getValue()));
	lang.entrySet().forEach(s -> result.add(s.getKey(), s.getValue()));
	JsonObject merged = result.build();
	assertThat(merged.getString("developer"), is("duke"));
	assertThat(merged.getString("language"), is("java"));
}

Adding additional attribute to a JsonObject instance works similarly.

See you at Java EE Workshops at Munich Airport, Terminal 2, particularly at: Effective Java EE 7! Is MUC too far? Checkout effectivejavaee.com