[英]Custom handler for response body in Jackson / Spring
I am trying to intercept the object that is being returned in my controller so that I can create a flat JSON structure of the response, before Spring invokes Jackson's serialization process. I am trying to intercept the object that is being returned in my controller so that I can create a flat JSON structure of the response, before Spring invokes Jackson's serialization process.
I am going to support a query parameter that allows the client to flatten the response body.我将支持一个允许客户端展平响应正文的查询参数。 Something like:就像是:
/v1/rest/employees/{employeId}/id?flat=true
The controller method looks something like: controller 方法如下所示:
public Employee getEmployee(...) {}
I would like to avoid implementing this flattening logic in every one of my service calls and continue to return the Employee
object.我想避免在我的每个服务调用中实现这种扁平化逻辑,并继续返回Employee
object。
Is there some kind of facility in Spring that would allow me to A) read the query string and B) intercept the object that is being returned as the response body? Spring 中是否有某种设施可以让我 A)读取查询字符串并 B)拦截作为响应正文返回的 object?
Here's one idea.这是一个想法。 There may be a better way, but this will work:可能有更好的方法,但这会起作用:
Define an extra request mapping to do the flat mapping:定义一个额外的请求映射来做平面映射:
@RequestMapping(path = "/endpoint", params = {"flat"})
public String getFlatThing() {
return flatMapper.writeValueAsString(getThing());
}
// The Jackson converter will do its ordinary serialization here.
@RequestMapping(path = "/endpoint")
public Thing getFlatThing() {
return new Thing();
}
the "flatMapper" implementation can be whatever you like so long as it works. “flatMapper”实现可以是任何你喜欢的,只要它有效。 One option is to use Jackson's ObjectMapper to write the value as json first and then use https://github.com/wnameless/json-flattener to flatten that to your desired output.一种选择是使用杰克逊的 ObjectMapper 首先将值写入 json 然后使用https://github.com/wnameless/json-flattener将其展平为所需的 Z78E6221F6393D1356Z.F681DB398 There may also be a way to define a custom ObjectMapper that does flat mapping, though that would take some more work on your part.也可能有一种方法可以定义一个执行平面映射的自定义 ObjectMapper,尽管这需要您做更多的工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.