adam bien's blog

Extracting Fragments from JSON Documents with JSON-P 📎

With Jakarta JSON Processing API (JSON-P) available in all Jakarta EE and MicroProfile runtimes, you can parse a JSON object:

import static org.junit.jupiter.api.Assertions.assertEquals;

import static javax.json.Json.*;
import java.io.StringReader;
import javax.json.JsonObject;
import javax.json.JsonReader;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

public class JSONPPointerTest {

    JsonObject json;

    @BeforeEach
    public void init() {
        var raw = this.getJSON();
        try(JsonReader reader = createReader(new StringReader(raw))){
            this.json = reader.readObject();
        }
    }

    String getJSON() {
        return """
                {
                    "base": {
                        "cpu.systemLoadAverage": 4.14208984375,
                        "thread.count": 45,
                        "gc.time;name=G1 Young Generation": 16
                        },
                    "references":["MP metrics","JSON-P","rfc6901","Jakarta EE","microprofile"]
                }
                """;
    }
    
    
...and use a JSON Pointer (rfc6901) to extract values from nested objects:
            
    @Test
    public void extractValueFromObject() {
        var pointer = createPointer("/base/thread.count");
        var fragment = pointer.getValue(this.json);
        assertEquals(createValue(45), fragment);
    }
    
...as well as, JSON arrays:

    @Test
    public void extractValueFromArray() {
        var pointer = createPointer("/references/1");
        var fragment = pointer.getValue(this.json);
        assertEquals(createValue("JSON-P"), fragment);
    }

}    
    
The JSON-P implementation already ships with all Jakarta EE 8 / Java EE 8 / MicroProfile runtimes. The single, test-scoped, dependency is only required to run the Unit Tests:

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

Also checkout: "Manipulating JsonObjects with JsonPatch"