1、根据url传参,返回需要的json数据
2、很少的配置,无需特殊处理(只需要几行代码)
可以通过传参 JSON-KEY=${xxx}
来控制返回数据,${xxx} 兼容jsonview查询语法,比如
curl http://localhost:8080/simpleCurd/test2?JSON-KEY=name,id
返回:
[
{
id: "1",
name: "kkkk"
},
{
id: "11",
name: "kkkk"
}
]
这里关键需要用到spring的 ResponseBodyAdvice
接口,对返回数据进行处理
核心代码如下:
@ControllerAdvice
public class MyRequestBodyAdviceAdapter implements ResponseBodyAdvice<Object> {
private final static String JSON_KEY_HEADER = "JSON-KEY";
@Resource
private MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter;
@PostConstruct
public void init() {
// 将JsonView加入到jackson的module当中
mappingJackson2HttpMessageConverter.getObjectMapper().registerModule(new JsonViewModule());
}
@Override
public boolean supports(MethodParameter returnType, Class converterType) {
return true;
}
@Override
public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
// JsonView 支持
String keys = RequestUtil.getRequest().getParameter(JSON_KEY_HEADER);
if (body != null && null != keys && keys.length() > 0) {
Class<?> clz = body.getClass();
if (body instanceof Collection) {
clz = ((Collection<?>)body).iterator().next().getClass();
}
body = JsonView.with(body).onClass(clz, Match.match().exclude("*").include(keys.split(",")));
}
// 统一结果封装
return body;
}
}
这里依赖了一个轻量的jsonview包:
<dependency>
<groupId>com.monitorjbl</groupId>
<artifactId>json-view</artifactId>
<version>1.0.1</version>
</dependency>