Jackson 中响应主体的自定义处理程序 / Spring
Custom handler for response body in Jackson / Spring
我正在尝试拦截正在我的控制器中 returned 的对象,以便我可以在 Spring 调用 Jackson 的序列化之前创建响应的平面 JSON 结构过程。
我将支持允许客户端扁平化响应主体的查询参数。类似于:
/v1/rest/employees/{employeId}/id?flat=true
控制器方法类似于:
public Employee getEmployee(...) {}
我想避免在我的每个服务调用中实施这种扁平化逻辑,并继续 return Employee
对象。
Spring 中是否有某种工具可以让我 A) 读取查询字符串和 B) 拦截正在 returned 作为响应主体的对象?
这是一个想法。可能有更好的方法,但这行得通:
定义一个额外的请求映射来做平面映射:
@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();
}
“flatMapper”实现可以是任何你喜欢的,只要它能工作。
一种选择是首先使用 Jackson 的 ObjectMapper 将值写入 json,然后使用 https://github.com/wnameless/json-flattener 将其展平为您想要的输出。可能还有一种方法可以定义一个自定义的 ObjectMapper 来进行平面映射,尽管这需要您做更多的工作。
我正在尝试拦截正在我的控制器中 returned 的对象,以便我可以在 Spring 调用 Jackson 的序列化之前创建响应的平面 JSON 结构过程。
我将支持允许客户端扁平化响应主体的查询参数。类似于:
/v1/rest/employees/{employeId}/id?flat=true
控制器方法类似于:
public Employee getEmployee(...) {}
我想避免在我的每个服务调用中实施这种扁平化逻辑,并继续 return Employee
对象。
Spring 中是否有某种工具可以让我 A) 读取查询字符串和 B) 拦截正在 returned 作为响应主体的对象?
这是一个想法。可能有更好的方法,但这行得通:
定义一个额外的请求映射来做平面映射:
@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();
}
“flatMapper”实现可以是任何你喜欢的,只要它能工作。 一种选择是首先使用 Jackson 的 ObjectMapper 将值写入 json,然后使用 https://github.com/wnameless/json-flattener 将其展平为您想要的输出。可能还有一种方法可以定义一个自定义的 ObjectMapper 来进行平面映射,尽管这需要您做更多的工作。