From String to JsonObject and Back with Jakarta JSON Processing (JSON-P)

To read a Java String with Jakarta JSON Processing (JSON-P) into a jakarta.json.JsonObject, add the following dependency to your pom (or e.g. Joy):


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

Now a JsonObject can be read from a String:

import java.io.StringReader;
import java.io.StringWriter;

import jakarta.json.Json;


var message = """            
    {"hello":"world"}
""";

var jsonReader = Json.createReader(new StringReader(message));
var messageAsJson = jsonReader.readObject();
assertEquals("world", messageAsJson.getString("hello"));

...and written back to its String representation:


var stringWriter = new StringWriter();
var jsonWriter = Json.createWriter(stringWriter);
jsonWriter.writeObject(messageAsJson);

var readMessage = stringWriter.toString();
assertEquals(message.trim(), readMessage);

Also checkout: Jakarta JSON Processing with Japanese Joy

Comments:

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