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


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 #

What about using putAll since JsonObject exnteds Map<String, JsonValue>

Posted by thatsIch on June 01, 2019 at 03:55 PM CEST #

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