【前言】

前后端分离是现在系统开发主流模式,上篇博文《SpringBoot集成Swagger》介绍了利器Swagger;这篇接着定义返回Json格式的规范;无规矩,不成方圆;有了好的规范前后端的开发效率将大大提高;

【返回Json结果规范化】

一、规范化的必要性

1、未规范化痛点:

返回格式杂乱,前后端不能用统一的工具类去处理,极大拖延联调进度;

2、规范化爽点:

返回格式统一,前后端都可以用统一的工具类去处理,极大推进了联调进度;

二、如何改造:

1、项目中增加Wrapper

/* * Copyright (c) 2019. zhanghan_java@163.com All Rights Reserved. * 项目名称:实战SpringBoot * 类名称:Wrapper.java * 创建人:张晗 * 联系方式:zhanghan_java@163.com * 开源地址: https://github.com/dangnianchuntian/springboot * 博客地址: https://blog.csdn.net/zhanghan18333611647 */package com.zhanghan.zhboot.util.wrapper;import com.fasterxml.jackson.annotation.JsonIgnore;import com.fasterxml.jackson.databind.annotation.JsonSerialize;import lombok.Data;import java.io.Serializable;/** * The class Wrapper. * * @param  the type parameter @author https://blog.csdn.net/zhanghan18333611647 */@Data@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)public class Wrapper implements Serializable {/** * 序列化标识 */private static final long serialVersionUID = 3782350118017398556L;/** * 成功码. */public static final int SUCCESS_CODE = 0;/** * 成功信息. */public static final String SUCCESS_MESSAGE = "操作成功";/** * 错误码. */public static final int ERROR_CODE = 1;/** * 错误信息. */public static final String ERROR_MESSAGE = "内部异常";/** * 编号. */private int code;/** * 信息. */private String message;/** * 结果数据 */private T result;/** * Instantiates a new wrapper. default code=0 */Wrapper() {this(SUCCESS_CODE, SUCCESS_MESSAGE);}/** * Instantiates a new wrapper. * * @param code    the code * @param message the message */Wrapper(int code, String message) {this(code, message, null);}/** * Instantiates a new wrapper. * * @param code    the code * @param message the message * @param result  the result */Wrapper(int code, String message, T result) {super();this.code(code).message(message).result(result);}/** * Sets the 编号 , 返回自身的引用. * * @param code the new 编号 * * @return the wrapper */private Wrapper code(int code) {this.setCode(code);return this;}/** * Sets the 信息 , 返回自身的引用. * * @param message the new 信息 * * @return the wrapper */private Wrapper message(String message) {this.setMessage(message);return this;}/** * Sets the 结果数据 , 返回自身的引用. * * @param result the new 结果数据 * * @return the wrapper */public Wrapper result(T result) {this.setResult(result);return this;}/** * 判断是否成功: 依据 Wrapper.SUCCESS_CODE == this.code * * @return code =0,true;否则 false. */@JsonIgnorepublic boolean success() {return Wrapper.SUCCESS_CODE == this.code;}/** * 判断是否成功: 依据 Wrapper.SUCCESS_CODE != this.code * * @return code !=0,true;否则 false. */@JsonIgnorepublic boolean error() {return !success();}}

2、项目中增加WrapMapper

/* * Copyright (c) 2019. zhanghan_java@163.com All Rights Reserved. * 项目名称:实战SpringBoot * 类名称:WrapMapper.java * 创建人:张晗 * 联系方式:zhanghan_java@163.com * 开源地址: https://github.com/dangnianchuntian/springboot * 博客地址: https://blog.csdn.net/zhanghan18333611647 */package com.zhanghan.zhboot.util.wrapper;import io.micrometer.core.instrument.util.StringUtils;/** * The class Wrap mapper. * * @author https://blog.csdn.net/zhanghan18333611647 */public class WrapMapper {    /**     * Instantiates a new wrap mapper.     */    private WrapMapper() {    }    /**     * Wrap.     *     * @param      the element type     * @param code    the code     * @param message the message     * @param o       the o     * @return the wrapper     */    public static  Wrapper wrap(int code, String message, E o) {        return new Wrapper<>(code, message, o);    }    /**     * Wrap.     *     * @param      the element type     * @param code    the code     * @param message the message     * @return the wrapper     */    public static  Wrapper wrap(int code, String message) {        return wrap(code, message, null);    }    /**     * Wrap.     *     * @param   the element type     * @param code the code     * @return the wrapper     */    public static  Wrapper wrap(int code) {        return wrap(code, null);    }    /**     * Wrap.     *     * @param  the element type     * @param e   the e     * @return the wrapper     */    public static  Wrapper wrap(Exception e) {        return new Wrapper<>(Wrapper.ERROR_CODE, e.getMessage(), null);    }    /**     * Un wrapper.     *     * @param      the element type     * @param wrapper the wrapper     * @return the e     */    public static  E unWrap(Wrapper wrapper) {        return wrapper.getResult();    }    /**     * Wrap ERROR. code=1     *     * @param  the element type     * @return the wrapper     */    public static  Wrapper error() {        return wrap(Wrapper.ERROR_CODE, Wrapper.ERROR_MESSAGE, null);    }    /**     * Error wrapper.     *     * @param      the type parameter     * @param message the message     * @return the wrapper     */    public static  Wrapper error(String message) {        return wrap(Wrapper.ERROR_CODE, StringUtils.isBlank(message) ? Wrapper.ERROR_MESSAGE : message, null);    }    /**     * Wrap SUCCESS. code=0     *     * @param  the element type     * @return the wrapper     */    public static  Wrapper ok() {        return new Wrapper<>();    }    /**     * Ok wrapper.     *     * @param  the type parameter     * @param o   the o     * @return the wrapper     */    public static  Wrapper ok(E o) {        return new Wrapper<>(Wrapper.SUCCESS_CODE, Wrapper.SUCCESS_MESSAGE, o);    }}

3、修改Controller的返回值(以CheckMobileController为例)

/* * Copyright (c) 2019. zhanghan_java@163.com All Rights Reserved. * 项目名称:实战SpringBoot * 类名称:CheckMobileController.java * 创建人:张晗 * 联系方式:zhanghan_java@163.com * 开源地址: https://github.com/dangnianchuntian/springboot * 博客地址: https://blog.csdn.net/zhanghan18333611647 */package com.zhanghan.zhboot.controller;import com.mysql.jdbc.StringUtils;import com.zhanghan.zhboot.controller.request.MobileCheckRequest;import com.zhanghan.zhboot.properties.MobilePreFixProperties;import com.zhanghan.zhboot.util.wrapper.WrapMapper;import com.zhanghan.zhboot.util.wrapper.Wrapper;import io.swagger.annotations.Api;import io.swagger.annotations.ApiOperation;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.validation.annotation.Validated;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import java.util.HashMap;import java.util.Map;@RestController@Api(value = "校验手机号控制器",tags = {"校验手机号控制器"})public class CheckMobileController {    @Autowired    private MobilePreFixProperties mobilePreFixProperties;    @ApiOperation(value="优雅校验手机号格式方式",tags = {"校验手机号控制器"})    @RequestMapping(value = "/good/check/mobile", method = RequestMethod.POST)    public Wrapper goodCheckMobile(@RequestBody @Validated MobileCheckRequest mobileCheckRequest) {        String countryCode = mobileCheckRequest.getCountryCode();        String proFix = mobilePreFixProperties.getPrefixs().get(countryCode);        if (StringUtils.isNullOrEmpty(proFix)) {            return WrapMapper.error("参数错误");        }        String mobile = mobileCheckRequest.getMobile();        Boolean isLegal = false;        if (mobile.startsWith(proFix)) {            isLegal = true;        }        Map map = new HashMap();        map.put("mobile", mobile);        map.put("isLegal", isLegal);        map.put("proFix", proFix);        return WrapMapper.ok(map);    }    @ApiOperation(value="扩展性差校验手机号格式方式",tags = {"校验手机号控制器"})    @RequestMapping(value = "/bad/check/mobile", method = RequestMethod.POST)    public Wrapper badCheckMobile(@RequestBody MobileCheckRequest mobileCheckRequest) {        String countryCode = mobileCheckRequest.getCountryCode();        String proFix;        if (countryCode.equals("CN")) {            proFix = "86";        } else if (countryCode.equals("US")) {            proFix = "1";        } else {            return WrapMapper.error("参数错误");        }        String mobile = mobileCheckRequest.getMobile();        Boolean isLegal = false;        if (mobile.startsWith(proFix)) {            isLegal = true;        }        Map map = new HashMap();        map.put("mobile", mobile);        map.put("isLegal", isLegal);        map.put("proFix", proFix);        return  WrapMapper.ok(map);    }}

三、效果展示:

1、启动项目访问 http://localhost:8080/swagger-ui.html

2、在swagger中访问 校验手机号控制器 中的方法

四、项目地址及代码版本:

1、地址:https://github.com/dangnianchuntian/springboot

2、代码版本:1.2.0-Release

【总结】

1、约定重要性;

2、观察在工作中最耗时的工作,不断优化,提高工作效率。

.net core json 为null输出_SpringBoot实战(九):标准化json返回值相关推荐

  1. ThinkPHP6项目基操(20.实战部分 数据库操作返回值总结)

    数据库操作返回值总结 0. 前言 1. Db类操作数据库 1.1 新增 1.2 更新 1.3 删除 1.3.1 单条删除 1.3.2 批量删除 1.4 查询 1.4.1 单笔记录 1.4.2 多笔记录 ...

  2. python定义函数后怎么输出_python中如何定义函数返回值

    返回值简介: 简单介绍print和return的区别,print仅仅是打印在控制台,而return则是将return后面的部分作为返回值作为函数的输出,可以用变量接走,继续使用该返回值做其它事. 函数 ...

  3. python的json格式输出_python中json格式数据输出实现方式

    python中json格式数据输出实现方式 主要使用json模块,直接导入import json即可. 小例子如下: #coding=UTF-8 import json info={} info[&q ...

  4. 【微信小程序】微信小程序的接口调入 获取太阳码 根据返回值的类型进行接收,微信接口可能直接返回图片,也可能返回一个错误信息的json,同时兼容处理这两种情况

    目录 事件起因 环境和工具 操作过程 解决办法 遇到的一点问题 结束语 事件起因 在开发一个关于微信小程序的过程中,有一个这样的需求,要求生成微信小程序的太阳码,然而这个东西的请求方式我们是这样的:我 ...

  5. linux python脚本返回,在C/python中执行linux命令并得到返回值以及输出

    一般来说,用shell的方便之处在于,能够直接调用linux系统命令,方便的得到结果. 但是shell scprit的约束重重(这里不再讲了).下面说一下在C和python中如何调用linux命令.得 ...

  6. java输出结果校验_2. Bean Validation声明式校验方法的参数、返回值

    你必须非常努力,才能干起来毫不费力.本文已被 https://www.yourbatman.cn 收录,里面一并有Spring技术栈.MyBatis.JVM.中间件等小而美的专栏供以免费学习. ✍前言 ...

  7. 使用说明 vector_C++核心准则编译边学-F.20 输出结果时应该使用返回值

    F.20: For "out" output values, prefer return values to output parameters(输出结果时更应该使用返回值而不是输 ...

  8. JSON数据序列化与反序列化实战

    一.关于JSON JSON(JavaScript Object Notation) 是一种轻量级的数据交换格式,易于人阅读和编写.是一种文件规范,绝大多数的编程语言均可以轻松读写.当然python也不 ...

  9. 基于 abp vNext 和 .NET Core 开发博客项目 - Blazor 实战系列(三)

    基于 abp vNext 和 .NET Core 开发博客项目 - Blazor 实战系列(三) 转载于:https://github.com/Meowv/Blog 上一篇完成了博客的主题切换,菜单和 ...

最新文章

  1. 用Python做一个翻译软件,还怕英语不好?
  2. MLP多层感知机 学习笔记
  3. 【企业管理】价值创造的两个轮子
  4. 【乐畅】工作积累 ---- 调节音量大小 (滑动条调节音量大小并保存起来 )
  5. 玩转GIT系列之【如何恢复windows系统下git的状态图标显示】
  6. 记一次vue项目yarn打包环境配置失效的解决方案
  7. MyBatis 传递多个参数
  8. 你家的饮水机,到底可以有多脏?
  9. oracle 查看数据库性能,oracle 11G使用statspack查看数据库的性能
  10. 参考文献要不要首行缩进_参考文献格式要求(2015-2016-2)
  11. dataframe中多列除以不同列_Python之DataFrame切片与索引实验
  12. Java讲课笔记23:Map接口及其实现类
  13. Android彻底组件化方案实践
  14. 义务劳动: CISA的翻译
  15. 12.Memcached 与 Redis 区别
  16. 区块链技术指南之分布式系统核心问题
  17. ubuntuv20启动界面美化_Win10 美化软件(简洁篇)
  18. OpenV2X 社区第一次线上交流会成功举办
  19. 浮点数取绝对值的方法
  20. 数字藏品NFT用的国内联盟链有哪些?

热门文章

  1. 2019-OO-第二单元总结
  2. Ubuntu:查询计算机软硬件信息
  3. Android wifi驱动的移植 realtek 8188
  4. webapi部署到IIS 404错误
  5. 现代软件工程 第一章 四则运算的实现--栈实现
  6. HDURevenge of Segment Tree(第二长的递增子序列)
  7. CString,int,string,char*之间的转换(转)
  8. 今天终于有自己的博客了!!!
  9. ICCV2021 还在用大量数据暴力train模型?主动学习,教你选出数据集中最有价值的样本...
  10. CVPR 2020丨更精准的视频目标检测:基于记忆增强的全局-局部整合网络的方法