Combining JsonObjects With JsonMerge and JSON-P

Combining both javax.json.JsonObject instances with "Java API for JSON Processing (JSR 374) / JSON-P":


import javax.json.Json;
import javax.json.JsonObject;
import static javax.json.Json.createObjectBuilder;
...

public class JsonMerge {

    @Test
    public void merge() {

        JsonObject runtime = createObjectBuilder().
            add("runtime", "Jakarta EE").
            add("speed", "lightspeed").
        build();

        JsonObject project = createObjectBuilder().
            add("project", "thinwars").
            add("dev", createObjectBuilder().
            add("name", "duke").
            add("age", 18)).
        build();

        JsonObject projectWithRuntime = Json.
            createMergePatch(runtime).
            apply(project).
        asJsonObject();

        assertThat(projectWithRuntime.getString("runtime"), equalTo("Jakarta EE"));
        assertThat(projectWithRuntime.getString("project"), equalTo("thinwars"));
        System.out.println(projectWithRuntime);
    }
}

Yields:


{
    "project": "thinwars",
    "dev": {
        "name": "duke",
        "age": 18
    },
    "runtime": "Jakarta EE",
    "speed": "lightspeed"
}    

Required dependencies in Java EE / MicroProfile environment: none

Unit Test setup requires the following dependency to JSON-P (reference) implementation:


<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>javax.json</artifactId>
    <version>1.1.4</version>
</dependency>

See you at Web, MicroProfile and Java EE Workshops at Munich Airport, Terminal 2 or Virtual Dedicated Workshops / consulting. Is Munich's airport too far? Learn from home: airhacks.io.


Web Apps, SPA, PWA with vanilla Java Script (ES 6+), CSS 3 and WebStandards only. As simple as possible, but not simpler. See you at: (Progressive) Web apps, Single Page Apps and WebStandards airhacks workshops at MUC airport, Winter Edition

airhacks.fm the podcast:

Stay in touch: airhacks.news.

Comments:

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