Java 17 String to JSON with Glassfish' jakarta.json

To read a Java String with Jakarta JSON Processing (JSON-P) into a jakarta.json.JsonObject with Glassfish' implementation add the following dependency to your pom.xml:


<dependency>
    <groupId>org.glassfish</groupId>
    <artifactId>jakarta.json</artifactId>
    <version>2.0.1</version>
</dependency>

Now a JsonObject can be created from a String:

import java.io.StringReader;
import org.junit.jupiter.api.Test;
import jakarta.json.Json;

public class JsonpWithGlassfishTest {

    @Test
    public void parseJSON() {
        var expected = "glassfish";
        var json = """
                {"hello":"%s"}
                """.formatted(expected);
                
        try (var stringReader = new StringReader(json)){
            var jsonObject = Json.createReader(stringReader).readObject();
            var actual = jsonObject.getString("hello");
            assertEquals(expected, actual);
        }
    }
}

Comments:

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