109-修改返回体的内容RestControllerAdvice
  TEZNKK3IfmPf 5天前 11 0

使用注解@RestControllerAdvice

新建自定义类:


/**
 * desc
 *
 * @author cjq
 * @date 2022/10/11
 */
@RestControllerAdvice(value={"com.xxx.sjcj"},annotations = {ResultWrapper.class})
public class CustomResponseBodyAdvice implements ResponseBodyAdvice<Object> {

    @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) {
        SjcjResponse res = new SjcjResponse();
        JSONObject bodyObj = JSONObject.parseObject(JSON.toJSONString(body));
        int code = bodyObj.getInteger("code");
        if(HttpStatus.SUCCESS!=code){
            res.setCode(RespEnum.UNKNOW_ERROR.getCod());
            res.setDes(bodyObj.getString("msg"));
        }
        return res.toString();
    }
}

在需要重构返回体的方法上加注解ResultWrapper

ResultWrapper类:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ResultWrapper {
}

使用在方法中:

    @PostMapping
    @ResultWrapper
    public AjaxResult addBatch(@RequestBody List<SjcjSyfwEntity> list){
    //... 省略
    }
【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 5天前 0

暂无评论

推荐阅读
  TEZNKK3IfmPf   2024年05月17日   34   0   0 json
  TEZNKK3IfmPf   2024年04月26日   36   0   0 json
  TEZNKK3IfmPf   2024年04月26日   30   0   0 序列化json
  TEZNKK3IfmPf   2024年05月17日   41   0   0 jsonmysql
  TEZNKK3IfmPf   2024年04月19日   58   0   0 idepython
TEZNKK3IfmPf