Skip to content

Instantly share code, notes, and snippets.

@scofier
Last active April 25, 2020 08:36
Show Gist options
  • Save scofier/289ca1287d3b7217668399bb304b0422 to your computer and use it in GitHub Desktop.
Save scofier/289ca1287d3b7217668399bb304b0422 to your computer and use it in GitHub Desktop.
如何实现自定义返回json数据,类似 JsonView

需求

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>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment