Java / JSON-B: String To JsonObject

With Jakarta JSON-P you have to use a JsonReader to indirectly "read" a String into a JsonObject.

Jakarta JSON Binding (JSON-B) directly supports the deserialization from a String into Java objects, also JsonObjects:


import jakarta.json.JsonObject;
import jakarta.json.bind.JsonbBuilder;

public class JsonpWithJsonb {

    @Test
    public void stringToJsonObject(){
        var serialized = """
        {"name":"duke"}
        """;

        var deserialized = JsonbBuilder
                            .create()
                            .fromJson(serialized,JsonObject.class);
        assertNotNull(deserialized);
        System.out.println(deserialized);
    }
    
}    

The test above is successful and prints: {"name":"duke"}

In a Java SE environment you need a single dependency (JSON-B RI) in your pom.xml:


<dependency>
    <groupId>org.eclipse</groupId>
    <artifactId>yasson</artifactId>
    <version>2.0.4</version>
</dependency>

Most Jakarta EE / MicroProfile runtimes are already shipping with JSON-B support.

Comments:

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