Spring Boot-3

学习笔记(今天又读了好多篇的博客,做个今天的总结,加油!!!)

PS:快到中伏了,今天还是好热

使用阿里巴巴 FastJson 的设置

1、jackson 和 fastJson 的对比

有很多人已经习惯于使用阿里巴巴的 fastJson 来做项目中 json 转换的相关工作,比如目前项目中使用的就是阿里的 fastJson

关于 fastJson 和 jackson 的对比,网上有很多资料可以查看,主要是根据自己实际项目情况来选择合适的框架。

从扩展上来看,fastJson 没有 jackson 灵活,从速度或者上手难度来看,fastJson 可以考虑,项目中目前使用的是阿里的 fastJson,挺方便的。

2、 fastJson 依赖导入

xml 复制代码
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
</dependency>

3 、使用 fastJson 处理 null

使用 fastJson 时,对 null 的处理和 jackson 有些不同,需要继承 WebMvcConfigurationSupport 类或者实现

WebMvcConfiguration 接口,然后覆盖 configureMessageConverters 方法,在方法中可以选择对要实现 null转换的场景,配置好即可。

java 复制代码
@Configuration
public class fastJsonConfig extends WebMvcConfigurationSupport {
//使用阿里 FastJson 作为 JSON MessageConverter
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig();
        config.setSerializerFeatures(
            SerializerFeature.WriteMapNullValue, // 保留 map 空的字段
            SerializerFeature.WriteNullStringAsEmpty, // 将 String 类型的 null 转成"" SerializerFeature.WriteNullNumberAsZero, // 将 Number 类型的 null 转成 0
            SerializerFeature.WriteNullListAsEmpty, // 将 List 类型的 null 转成[]
            SerializerFeature.WriteNullBooleanAsFalse, // 将 Boolean 类型的 null 转成 false
            SerializerFeature.DisableCircularReferenceDetect); // 避免循环引用
        converter.setFastJsonConfig(config);
        converter.setDefaultCharset(Charset.forName("UTF-8"));
        List<MediaType> mediaTypeList = new ArrayList<>();
// 解决中文乱码问题,相当于在 Controller 上的@RequestMapping 中加了个属性 produces ="application/json" 
        mediaTypeList.add(MediaType.APPLICATION_JSON);
        converter.setSupportedMediaTypes(mediaTypeList);
        converters.add(converter);
    }
}

测试工具 postman

java 复制代码
@PostMapping
public String create(@RequestBody User user){
    //@RequestBody要求传入的数据必须为json
    boolean bb = userService.create(user);
    if(bb)
        return "success"
    return "failure";
}

如果直接测试,则需要编写页面和 js 代码才能进行验证,可以使用postman 避免这些繁琐的操作

这里针对日期类型数据的格式转换会有报错。最终提交数据为

{"username":"谢逊","sex":"true","birth":"1989-02-03","password":"666666"}

4、封装统一返回的数据结构

在实际项目中,除了要封装数据之外,往往需要在返回的 json 中添加一些其他信息,比如返回一些状态码 code【注意不是 response 的响应状态码】,返回一些 msg 给调用者,这样调用者可以根据 code 或者 msg 做一些逻辑判断。所以在实际项目中,需要封装一个统一的 json 返回结构存储返回信息。

4.1 定义统一的 json 结构

由于封装的 json 数据的类型不确定,所以在定义统一的 json 结构时需要用到泛型。统一的 json 结构中属性包括数据、状态码、提示信息即可,构造方法可以根据实际业务需求做相应的添加即可,一般来说,应该有默认的返回结构,也应该有用户指定的返回结构。

java 复制代码
public class JsonResult<T> {
    private T data; //需要传递的数据
    private int code; 
//用户自定义相应码,注意不是服务器响应状态码。
//如果不需要传递详细信息还可以使用 boolean success;
    private String msg; // 服务器回传信息
    public JsonResult() { 
//若没有数据返回,默认状态码为 0,提示信息为:操作成功!
        this.code = 0;
        this.msg = "操作成功!";
    }
    public JsonResult(int code, String msg) { //若没有数据返回,可以人为指定状态码和提示信息
        this.code = code;
        this.msg = msg;
    }
    public JsonResult(T data) { 有数据返回时,状态码为 0,默认提示信息为:操作成功!
        this.data = data;
        this.code = 0;
        this.msg = "操作成功!";
    }
    public JsonResult(T data, String msg) { 有数据返回,状态码为 0,人为指定提示信息
        this.data = data;
        this.code = 0;
        this.msg = msg;
    }
    // 省略 get 和 set 方法
}

建议写法,不一定最佳

java 复制代码
@Data
public class JsonReault implements Serializable{
    private Boolean success;
    private Integer code;
    private Object data;
    private String message;
}

4.2 修改 Controller 中的返回值类型及测试

由于 JsonResult 使用了泛型,所以所有的返回值类型都可以使用该统一结构,在具体的场景将泛型替换成具体的数据类型即可,非常方便,也便于维护。在实际项目中,还可以继续封装,比如状态码和提示信息可以定义一个枚举类型,以后只需要维护这个枚举类型中的数据即可。根据以上的 JsonResult 可以改写一下 Controller

java 复制代码
@RestController
@RequestMapping("/jsonresult")
public class JsonResultController {
    @RequestMapping("/user")
    public JsonResult<User> getUser() {
        User user = new User(1, "羊羊", "123456");
        return new JsonResult<>(user);
    }
    @RequestMapping("/list")
    public JsonResult<List> getUserList() {
        List<User> userList = new ArrayList<>();
        User user1 = new User(1, "羊羊", "123456");
        User user2 = new User(2, "小灰灰", "123456");
        userList.add(user1);
        userList.add(user2);
        return new JsonResult<>(userList, "获取用户列表成功");
    }
    @RequestMapping("/map")
    public JsonResult<Map> getMap() {
        Map<String, Object> map = new HashMap<>(3);
        User user = new User(1, "羊羊", null);
        map.put("作者信息", user);
        map.put("博客地址", "http://blog.yang.com");
        map.put("CSDN 地址", null);
        map.put("粉丝数量", 4153);
        return new JsonResult<>(map);
    }
}  

重新在浏览器中输入:localhost:8080/jsonresult/user 返回 json:

{"code":0,"data":{"id":1,"password":"123456","username":"羊羊"},"msg":"操作成功!"}

输入:localhost:8080/jsonresult/list,返回 json 格式:

{"code":0, "data":[{"id":1, "password":"123456", "username":" 羊羊 "}, {"id":2, "password":"123456","username":"小灰灰"}], "msg":"获取用户列表成功"}

输入:localhost:8080/jsonresult/map,返回 json 格式:

{"code":"0", "data":{"作者信息":{"id":1, "password":"","username":"羊羊"},"CSDN 地址":null,"粉丝数量

":4153,"博客地址":"http://blog.yang.com"},"msg":"操作成功!"}

通过封装,不但将数据通过 json 传给前端或者其他接口,还带上了状态码和提示信息,这在实际项目场景中应用非常广泛。

总结

这里主要是对 Spring Boot 中 json 数据的返回做了详细的分析,从 Spring Boot 默认的 jackson 框架到阿里的fastJson 框架,分别对它们的配置做了相应的描述。另外,结合实际项目情况,总结了实际项目中使用的 json封装结构体,加入了状态码和提示信息,使得返回的 json 数据信息更加完整。

相关推荐
青灯文案140 分钟前
如何在 SpringBoot 项目创建并使用 Redis 的详细介绍
spring boot·redis·bootstrap
念言-ny1 小时前
sentinel小记
java·spring boot·sentinel
m0_748250741 小时前
Spring Boot 多数据源解决方案:dynamic-datasource-spring-boot-starter 的奥秘(上)
java·spring boot·后端
m0_748254092 小时前
Spring Boot 中使用 @Transactional 注解配置事务管理
数据库·spring boot·sql
总是学不会.4 小时前
EasyExcel 使用指南:基础操作与常见问题
java·开发语言·数据库·后端·mysql
️○-4 小时前
后端之JPA(EntityGraph+JsonView)
java·数据库·后端·数据库架构
m0_748240914 小时前
Docker部署Spring Boot + Vue项目
vue.js·spring boot·docker
找了一圈尾巴4 小时前
Spring Boot 概要(官网文档解读)
java·spring boot·架构
库库林_沙琪马5 小时前
Spring Boot Validation 接口校验:从零到掌握
java·前端·spring boot
my_styles5 小时前
2025-spring boot 之多数据源管理
java·spring boot·后端