Maven Coordinates
To enable JSON-B Support add the following dependency to your project’s pom.xml (see Managing Dependencies).
<dependency>
<groupId>io.helidon.media</groupId>
<artifactId>helidon-media-jsonb</artifactId>
</dependency>JSON-B Support
The WebServer supports the JSON-B specification. When this support is enabled, Java objects will be serialized to and deserialized from JSON automatically using Yasson, an implementation of the JSON-B specification.
Usage
To enable JSON-B support, first create and register a JsonbSupport instance with a WebServer.Builder.
JsonbSupport via WebServerJsonbSupport jsonbSupport = JsonbSupport.create();
WebServer webServer = WebServer.builder()
.addMediaSupport(jsonbSupport)
.build();- Create a
JsonbSupportinstance. This instance may be reused freely. - Register that
JsonbSupportinstance to enable automatic deserialization of Java objects from and serialization of Java objects to JSON.
Now that automatic JSON serialization and deserialization facilities have been set up, you can register a Handler that works with Java objects instead of raw JSON. Deserialization from and serialization to JSON will be handled according to the JSON-B specification.
Suppose you have a Person class that looks like this:
Person classpublic class Person {
private String name;
public Person() {
super();
}
public String getName() {
return this.name;
}
public void setName(final String name) {
this.name = name;
}
}Then you can set up a Handler like this:
Handler that works with Java objects instead of raw JSONfinal Routing routing =
routingBuilder.post("/echo",
Handler.create(Person.class,
(req, res, person) -> res.send(person))))
.build();- Set up a route for
POSTrequests using theRouting.Builder#post(String, Handler…)method - Use the
Handler#create(Class, Handler.EntityHandler)method to install aHandler.EntityHandlerthat works withPersoninstances. - This
Handler.EntityHandlerconsumes aPersoninstance (person) and simply echoes it back. Note that there is no working with raw JSON here.
/echo endpointcurl --noproxy '*' -X POST -H "Content-Type: application/json" \
http://localhost:8080/echo -d '{"name":"Joe"}'
{"name":"Joe"}