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>content_copy
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();content_copy
- Register JsonpSupport to enable transformation from and to
JsonObjectobjects - 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);
}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 JsonpSupport instance, create the JsonpSupport object:
Create
JsonpSupport with the provided configurationJsonpSupport.create(Map.of(JsonGenerator.PRETTY_PRINTING, false))content_copy