SpringBoot实战(九):标准化json返回值

简介: SpringBoot实战(九):标准化json返回值

强烈推荐一个大神的人工智能的教程:http://www.captainai.net/zhanghan


【前言】


      前后端分离是现在系统开发主流模式,上篇博文《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 <T> the type parameter @author https://blog.csdn.net/zhanghan18333611647
 */
@Data
@JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
public class Wrapper<T> 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<T> code(int code) {
  this.setCode(code);
  return this;
  }
  /**
  * Sets the 信息 , 返回自身的引用.
  *
  * @param message the new 信息
  *
  * @return the wrapper
  */
  private Wrapper<T> message(String message) {
  this.setMessage(message);
  return this;
  }
  /**
  * Sets the 结果数据 , 返回自身的引用.
  *
  * @param result the new 结果数据
  *
  * @return the wrapper
  */
  public Wrapper<T> result(T result) {
  this.setResult(result);
  return this;
  }
  /**
  * 判断是否成功: 依据 Wrapper.SUCCESS_CODE == this.code
  *
  * @return code =0,true;否则 false.
  */
  @JsonIgnore
  public boolean success() {
  return Wrapper.SUCCESS_CODE == this.code;
  }
  /**
  * 判断是否成功: 依据 Wrapper.SUCCESS_CODE != this.code
  *
  * @return code !=0,true;否则 false.
  */
  @JsonIgnore
  public 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 <E>     the element type
     * @param code    the code
     * @param message the message
     * @param o       the o
     * @return the wrapper
     */
    public static <E> Wrapper<E> wrap(int code, String message, E o) {
        return new Wrapper<>(code, message, o);
    }
    /**
     * Wrap.
     *
     * @param <E>     the element type
     * @param code    the code
     * @param message the message
     * @return the wrapper
     */
    public static <E> Wrapper<E> wrap(int code, String message) {
        return wrap(code, message, null);
    }
    /**
     * Wrap.
     *
     * @param <E>  the element type
     * @param code the code
     * @return the wrapper
     */
    public static <E> Wrapper<E> wrap(int code) {
        return wrap(code, null);
    }
    /**
     * Wrap.
     *
     * @param <E> the element type
     * @param e   the e
     * @return the wrapper
     */
    public static <E> Wrapper<E> wrap(Exception e) {
        return new Wrapper<>(Wrapper.ERROR_CODE, e.getMessage(), null);
    }
    /**
     * Un wrapper.
     *
     * @param <E>     the element type
     * @param wrapper the wrapper
     * @return the e
     */
    public static <E> E unWrap(Wrapper<E> wrapper) {
        return wrapper.getResult();
    }
    /**
     * Wrap ERROR. code=1
     *
     * @param <E> the element type
     * @return the wrapper
     */
    public static <E> Wrapper<E> error() {
        return wrap(Wrapper.ERROR_CODE, Wrapper.ERROR_MESSAGE, null);
    }
    /**
     * Error wrapper.
     *
     * @param <E>     the type parameter
     * @param message the message
     * @return the wrapper
     */
    public static <E> Wrapper<E> error(String message) {
        return wrap(Wrapper.ERROR_CODE, StringUtils.isBlank(message) ? Wrapper.ERROR_MESSAGE : message, null);
    }
    /**
     * Wrap SUCCESS. code=0
     *
     * @param <E> the element type
     * @return the wrapper
     */
    public static <E> Wrapper<E> ok() {
        return new Wrapper<>();
    }
    /**
     * Ok wrapper.
     *
     * @param <E> the type parameter
     * @param o   the o
     * @return the wrapper
     */
    public static <E> Wrapper<E> 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中访问 校验手机号控制器 中的方法


3672dc1b8ae866d46ca7565f1d6605c9_watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3UwMTI4MjkxMjQ=,size_16,color_FFFFFF,t_70.png


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


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


              2、代码版本:1.2.0-Release


【总结】


        1、约定重要性;


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


相关文章
|
JSON Java 数据格式
微服务——SpringBoot使用归纳——Spring Boot返回Json数据及数据封装——封装统一返回的数据结构
本文介绍了在Spring Boot中封装统一返回的数据结构的方法。通过定义一个泛型类`JsonResult&lt;T&gt;`,包含数据、状态码和提示信息三个属性,满足不同场景下的JSON返回需求。例如,无数据返回时可设置默认状态码&quot;0&quot;和消息&quot;操作成功!&quot;,有数据返回时也可自定义状态码和消息。同时,文章展示了如何在Controller中使用该结构,通过具体示例(如用户信息、列表和Map)说明其灵活性与便捷性。最后总结了Spring Boot中JSON数据返回的配置与实际项目中的应用技巧。
1223 0
|
JSON Java fastjson
微服务——SpringBoot使用归纳——Spring Boot返回Json数据及数据封装——使用 fastJson 处理 null
本文介绍如何使用 fastJson 处理 null 值。与 Jackson 不同,fastJson 需要通过继承 `WebMvcConfigurationSupport` 类并覆盖 `configureMessageConverters` 方法来配置 null 值的处理方式。例如,可将 String 类型的 null 转为 &quot;&quot;,Number 类型的 null 转为 0,避免循环引用等。代码示例展示了具体实现步骤,包括引入相关依赖、设置序列化特性及解决中文乱码问题。
947 0
|
JSON Java fastjson
微服务——SpringBoot使用归纳——Spring Boot返回Json数据及数据封装——Spring Boot 默认对Json的处理
本文介绍了在Spring Boot中返回Json数据的方法及数据封装技巧。通过使用`@RestController`注解,可以轻松实现接口返回Json格式的数据,默认使用的Json解析框架是Jackson。文章详细讲解了如何处理不同数据类型(如类对象、List、Map)的Json转换,并提供了自定义配置以应对null值问题。此外,还对比了Jackson与阿里巴巴FastJson的特点,以及如何在项目中引入和配置FastJson,解决null值转换和中文乱码等问题。
2002 0
|
JSON Java 数据格式
Spring Boot返回Json数据及数据封装
在Spring Boot中,接口间及前后端的数据传输通常使用JSON格式。通过@RestController注解,可轻松实现Controller返回JSON数据。该注解是Spring Boot新增的组合注解,结合了@Controller和@ResponseBody的功能,默认将返回值转换为JSON格式。Spring Boot底层默认采用Jackson作为JSON解析框架,并通过spring-boot-starter-json依赖集成了相关库,包括jackson-databind、jackson-datatype-jdk8等常用模块,简化了开发者对依赖的手动管理。
1014 3
|
数据采集 JSON 数据可视化
JSON数据解析实战:从嵌套结构到结构化表格
在信息爆炸的时代,从杂乱数据中提取精准知识图谱是数据侦探的挑战。本文以Google Scholar为例,解析嵌套JSON数据,提取文献信息并转换为结构化表格,通过Graphviz制作技术关系图谱,揭示文献间的隐秘联系。代码涵盖代理IP、请求头设置、JSON解析及可视化,提供完整实战案例。
1078 4
JSON数据解析实战:从嵌套结构到结构化表格
|
缓存 NoSQL Java
springboot怎么使用rides缓存方法的返回值 完整例子
通过上述步骤,我们成功地在 Spring Boot 项目中集成了 Redis 缓存,并通过注解的方式实现了方法返回值的缓存。这种方式不仅提高了系统的性能,还简化了缓存管理的复杂度。使用 Spring Boot 的缓存注解和 Redis,可以轻松地实现高效、可靠的缓存机制。
520 23
|
JSON Java 数据格式
微服务——SpringBoot使用归纳——Spring Boot中的全局异常处理——定义返回的统一 json 结构
本课主要讲解Spring Boot中的全局异常处理方法。在项目开发中,各层操作难免会遇到各种异常,若逐一处理将导致代码耦合度高、维护困难。因此,需将异常处理从业务逻辑中分离,实现统一管理与友好反馈。本文通过定义一个简化的JsonResult类(含状态码code和消息msg),结合全局异常拦截器,展示如何封装并返回标准化的JSON响应,从而提升代码质量和用户体验。
468 0
|
JSON Java 数据格式
springboot中表字段映射中设置JSON格式字段映射
springboot中表字段映射中设置JSON格式字段映射
928 1
|
JSON Java API
解码Spring Boot与JSON的完美融合:提升你的Web开发效率,实战技巧大公开!
【8月更文挑战第29天】Spring Boot作为Java开发的轻量级框架,通过`jackson`库提供了强大的JSON处理功能,简化了Web服务和数据交互的实现。本文通过代码示例介绍如何在Spring Boot中进行JSON序列化和反序列化操作,并展示了处理复杂JSON数据及创建RESTful API的方法,帮助开发者提高效率和应用性能。
1077 0
|
JSON Java API
Jackson:SpringBoot中的JSON王者,优雅掌控数据之道
【8月更文挑战第29天】在Java的广阔生态中,SpringBoot以其“约定优于配置”的理念,极大地简化了企业级应用的开发流程。而在SpringBoot处理HTTP请求与响应的过程中,JSON数据的序列化和反序列化是不可或缺的一环。在众多JSON处理库中,Jackson凭借其高效、灵活和强大的特性,成为了SpringBoot中处理JSON数据的首选。今天,就让我们一起深入探讨Jackson如何在SpringBoot中优雅地控制JSON数据。
882 0

热门文章

最新文章