adam bien's blog

Java EE 8: Manipulating JsonObjects with JsonPatch 📎

JSON-P (JSR-374) from Java EE 8 comes with JSON Patch support, which can be used for manipulation (patching) of JsonObject instances (see also Java EE 8 and JSON-P Simplify System Testing with JSON Patch):


@Test
public void patch() {
    JsonObject sub = Json.createObjectBuilder().
            add("name", "EE4J").
            build();

    JsonObject initial = Json.createObjectBuilder().
            add("fact", "Java EE is nice").
            add("myth", "Java EE is heavyweight").
            add("future", sub).
            build();

    JsonPatch patch = Json.createPatchBuilder().
            add("/version", "8").
            replace("/fact", "Java EE rocks").
            replace("/future/name", "Jakarta EE").
            remove("/myth").
            build();

    JsonObject result = patch.apply(initial);
    System.out.println("result = " + result);
}

Output:

result = {"fact":"Java EE rocks","future":{"name":"Jakarta EE"},"version":"8"}

JSON-P comes as a single maven dependency:


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

See you at Java EE Workshops at MUC Airport, particularly at the Effective Java EE 8 workshop