Maven Coordinates

To enable JSON Support add the following dependency to your project’s pom.xml (see Managing Dependencies).

<dependency>
    <groupId>io.helidon.media</groupId>
    <artifactId>helidon-media-jsonp</artifactId>
</dependency>
Copied

Json Support

The WebServer supports JSON-P. When enabled, you can send and receive JSON-P objects transparently.

Usage

To enable JSON-P support, first register it with the web server. Then you can add routes that handle and return JSON.

Configure JsonpSupport and use it for reading and writing of entities
JsonpSupport jsonbSupport = JsonpSupport.create(); 
WebServer webServer = WebServer.builder()
    .addMediaSupport(jsonpSupport) 
    .build();
Copied
  • Register JsonpSupport to enable transformation from and to JsonObject objects
  • Register that JsonpSupport instance to enable automatic deserialization of Java objects from and serialization of Java objects to JSON.
Handler that receives and returns JSON objects
private static final JsonBuilderFactory JSON_FACTORY = Json.createBuilderFactory(Collections.emptyMap()); 

private void sayHello(ServerRequest req, ServerResponse res, JsonObject json) { 
        JsonObject msg = JSON_FACTORY.createObjectBuilder()   
          .add("message", "Hello " + json.getString("name"))
          .build();
        res.send(msg);                            
}
Copied
  • Using a JsonBuilderFactory is more efficient than Json.createObjectBuilder()
  • JsonObject is passed to handler
  • Create a JsonObject using JSON-P to hold return data
  • Send JsonObject in response
Example of posting JSON to sayHello endpoint
curl --noproxy '*' -X POST -H "Content-Type: application/json" \
    http://localhost:8080/sayhello -d '{"name":"Joe"}'
{"message":"Hello Joe"}
Copied

Configuring Json Reader/Writer factories

To configure JSON-P JsonReaderFactory and JsonWriterFactory that are used by the JsonpSupport instance, create the JsonpSupport object:

Create JsonpSupport with the provided configuration
JsonpSupport.create(Map.of(JsonGenerator.PRETTY_PRINTING, false))
Copied