Interface RequestBodyMarshaler
- All Known Implementing Classes:
DefaultRequestBodyMarshaler
- Functional Interface:
- This is a functional interface and can therefore be used as the assignment target for a lambda expression or method reference.
Contract for converting request body bytes into a corresponding Java type.
For example, if your Resource Methods expect JSON request bodies like this (note the RequestBody
annotation):
@POST("/find-biggest")
public Integer findBiggest(@RequestBody List<Integer> numbers) {
// JSON request body [1,2,3] results in 3 being returned
return Collections.max(numbers);
}
You might implement a RequestBodyMarshaler
to accept JSON like this:
SokletConfiguration config = SokletConfiguration.withServer(
DefaultServer.withPort(8080).build()
).requestBodyMarshaler(new RequestBodyMarshaler() {
// This example uses Google's GSON
static final Gson GSON = new Gson();
@Nonnull
@Override
public Optional<Object> marshalRequestBody(
@Nonnull Request request,
@Nonnull ResourceMethod resourceMethod,
@Nonnull Parameter parameter,
@Nonnull Type requestBodyType
) {
// Let GSON turn the request body into an instance
// of the specified type.
//
// Note that this method has access to all runtime information
// about the request, which provides the opportunity to, for example,
// examine annotations on the method/parameter which might
// inform custom marshaling strategies.
return Optional.of(GSON.fromJson(
request.getBodyAsString().get(),
requestBodyType
));
}
}).build();
See https://www.soklet.com/docs/request-handling#request-body for detailed documentation.
- Author:
- Mark Allen
-
Method Summary
Modifier and TypeMethodDescriptionmarshalRequestBody
(Request request, ResourceMethod resourceMethod, Parameter parameter, Type requestBodyType) Given a request, the Resource Method that will handle it, and aRequestBody
-annotated parameter + its type, convert the request body bytes into an instance of typerequestBodyType
.
-
Method Details
-
marshalRequestBody
@Nonnull Optional<Object> marshalRequestBody(@Nonnull Request request, @Nonnull ResourceMethod resourceMethod, @Nonnull Parameter parameter, @Nonnull Type requestBodyType) Given a request, the Resource Method that will handle it, and aRequestBody
-annotated parameter + its type, convert the request body bytes into an instance of typerequestBodyType
.This instance will be injected by Soklet when it invokes the Resource Method to handle the request.
- Parameters:
request
- the request whose body should be converted into a Java typeresourceMethod
- the Resource Method that is configured to handle the requestparameter
- the Resource Method parameter into which the returned instance will be injectedrequestBodyType
- the type of the Resource Method parameter (provided for convenience)- Returns:
- the Java instance that corresponds to the request body bytes suitable for assignment to the Resource Method parameter, or
Optional.empty()
if no instance should be marshaled
-