Akka拒绝处理程序返回JSON响应

时间:2019-04-29 10:55:58

标签: java akka

我正在尝试使用Akka HTTP,并且是从官方doc找到的,代码段如下所示

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;
    }
});

现在,我陷入了需要将JSON类型转换为“更干净”而不是字符串串联的地方。

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

我知道我可以使用ObjectMapper(),但是我正在寻找一种完成工作的默认方法。一种神奇的调味方法,需要Marshaller,类和对象来完成。 有什么想法吗?

到目前为止,我已经尝试过类似的事情

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

HttpResponse httpResponse = HttpResponse.create()
                           .withStatus(response.status().intValue())
                           .withEntity(jsonMessage);
return httpResponse;

但是,尽管内容标头已设置为Content-Type→application / json,但我仍然收到了text / plain响应。

0 个答案:

没有答案