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>content_copy
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();content_copy
- Register JsonSupport to enable transformation from and to
JsonObjectobjects - Register a handler that receives a
JsonObjectas 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);
}content_copy
- Using a
JsonBuilderFactoryis more efficient thanJson.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"}content_copy
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 configurationJsonSupport.create(Map.of(JsonGenerator.PRETTY_PRINTING, false))content_copy