How to merge javax.json.JsonObject instances

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

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

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

NEW: Online Workhop Effective WebApps without Frameworks is also coming to: MUC Airport.

Airport MUC workshops: Web (SPA, PWAs, Offline, Desktop, Mobile) Applications Essentials and Effective Web Applications. No migrations. #usetheplatform

Podcast: and newsletter:

A book about rethinking Java EE Patterns


You could use forEach directly on JsonObject making it slightly more compact:

dev.forEach((k,v) -> result.add(k, v));

Posted by Michael Nascimento Santos on August 10, 2016 at 03:38 AM CEST #

Post a Comment:
  • HTML Syntax: NOT allowed
Online Workshops
...the last 150 posts
...the last 10 comments