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


NEW online workshop: WebStandards Igniter (online)

Airport MUC workshops: Java EE 7: Bootstrap, Effective, Architectures, Web, React and Angular, Testing and Microservices

Podcast: airhacks.fm and newsletter: airhacks.news

A book about rethinking Java EE Patterns

Comments:

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
realworldpatterns.com
Online Workshops
...the last 150 posts
...the last 10 comments
License