Rapidoid。如何在不渲染的情况下从lambda返回响应?

时间:2017-08-20 13:45:57

标签: java http server

我需要从lambda返回一个响应而不需要额外的渲染。我试着这样做:

On.post("/locations/{id:\\d+}").serve((Integer id, Req req, Resp resp) -> {
    if (!storageService.locationIsPresent(id)) {
        return resp.code(404).json("Location not found!");
    }
    try {
        String request = new String(req.body());
        Location location = mapper.readValue(request, Location.class);
        storageService.updateLocation(id, location.getCountry(), location.getCity(), location.getPlace(), location.getDistance() );
    } catch (Exception ex) {
        return resp.code(400).json("Bad request!");
    }
    return resp.code(200).body(EMPTY_RESP);
});

但结果我得到了一个例外:

ERROR | 20/Aug/2017 14:19:53:460 | executor2 | org.rapidoid.http.impl.lowlevel.LowLevelHttpIO | Error occurred when handling request! | error = java.lang.RuntimeException: com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.rapidoid.http.impl.RespImpl and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS) java.lang.RuntimeException: com.fasterxml.jackson.databind.JsonMappingException: No serializer found for class org.rapidoid.http.impl.RespImpl and no properties discovered to create BeanSerializer (to avoid exception, disable SerializationFeature.FAIL_ON_EMPTY_BEANS)

请告诉我如何正确地做到这一点。

我还想知道如何配置服务器以获得更快的响应,每秒有大量请求。因为在我的情况下它很慢。

提前谢谢!

2 个答案:

答案 0 :(得分:1)

尝试按以下方式配置您的映射器,     ObjectMapper mapper = new ObjectMapper(); mapper.setVisibility(PropertyAccessor.FIELD, Visibility.ANY); 这是关于这个问题的一些信息, http://www.baeldung.com/jackson-exception

答案 1 :(得分:1)

请回答我的旧问题,并决定分享解决方案。 要返回预序列化的JSON,可以这样做:

On.get("/").serve((Integer id, Req req, Resp resp) -> {
   byte[] hardcodedJSON = "{\"x\": 123}".getBytes();
   return resp.contentType(MediaType.JSON).body(hardcodedJSON);
});