I'm trying out things with Akka HTTP and I found this from the official doc and the snippet code goes like this

final RejectionHandler rejectionHandler = RejectionHandler.defaultHandler()
    .mapRejectionResponse(response -> {
    if (response.entity() instanceof HttpEntity.Strict) {
        // since all Akka default rejection responses are Strict this will handle all rejections
        String message = ((HttpEntity.Strict) response.entity()).getData().utf8String()
            .replaceAll("\"", "\\\"");
        // we create a new copy the response in order to keep all headers and status code,
        // replacing the original entity with a custom message as hand rolled JSON you could the
        // entity using your favourite marshalling library (e.g. spray json or anything else)
        return response.withEntity(ContentTypes.APPLICATION_JSON,
            "{\"rejection\": \"" + message + "\"}");
    } else {
        // pass through all other types of responses
        return response;

Now I'm stuck where I need to convert the JSON type something 'cleaner' rather than string concatenation.

return response.withEntity(ContentTypes.APPLICATION_JSON,
    "{\"rejection\": \"" + message + "\"}");

I know I can use ObjectMapper() but I'm looking into a default way of gettings things done. The magic sauce method which would take Marshaller, class and the object to get the things done. Any ideas?

So far I've tried something like this

String message = ((HttpEntity.Strict) response.entity()).getData().utf8String();
HttpEntity.Strict jsonMessage = HttpEntities.create(ContentTypes.APPLICATION_JSON, message);

HttpResponse httpResponse = HttpResponse.create()
return httpResponse;

But still, I get the text/plain response though content headers has been set to Content-Type →application/json.

0 Answers