Json Support

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

Maven Coordinates

Declare the following dependency in your project:

Webserver JSON-P Dependency
<dependency>
    <groupId>io.helidon.media.jsonp</groupId>
    <artifactId>helidon-media-jsonp-server</artifactId>
</dependency>
Copied

Usage

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

Configure JsonSupport and use it for reading and writing of entities
Routing.builder()
       .register(JsonSupport.create()) 
       .post("/sayhello", Handler.create(JsonObject.class, this::sayHello)) 
       .build();
Copied
  • Register JsonSupport to enable transformation from and to JsonObject objects
  • Register a handler that receives a JsonObject as its input.
Handler that receives and returns JSON objects
private static final JsonBuilderFactory jsonFactory = Json.createBuilderFactory(Collections.emptyMap()); 

private void sayHello(ServerRequest req, ServerResponse res, JsonObject json) { 
        JsonObject msg = jsonFactory.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 JsonSupport instance, create the JsonSupport object:

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