当前位置: 首页 > news >正文

博客摘录「 Springboot入门到精通(超详细文档)」2025年7月4日

1.Spring Boot返回Json数据及数据封装

1. Controller 中使用@RestController注解即可返回 Json 格式的数据

首先看看@RestController注解包含了什么东西, @ResponseBody 注解是将返回的数据结构转换为 Json 格式

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {@AliasFor(annotation = Controller.class)String value() default "";
}

Spring Boot 中默认使用的 json 解析框架是 jackson

1.1 Spring Boot 默认对Json的处理

1.1.1 创建实体类

@Data
public class Student {public int studentId;public String studentName;
}

 1.1.2 创建接口类

@RestController
@CrossOrigin
@RequestMapping("/json")
public class JsonTest {@RequestMapping("/getStudent")public Student getStudent() {return new Student(18, "小志");}@RequestMapping("/getStudentList")public List<Student> getStudentList() {List<Student> list = new ArrayList<>();list.add(new Student(18, "小志"));list.add(new Student(19, "小庄"));list.add(new Student(20, "小王"));return list;}@RequestMapping("/getStudentMap")public Map<String,Object> getStudentMap() {Map<String,Object> map = new HashMap();map.put("学生姓名",new Student(25,"小王"));map.put("家庭地址","厦门市惠安县");map.put("出生年月",202000326);return map;}}

 1.1.3 结果展示


-- /json/getStudent
{"studentId":18,"studentName":"小志"}-- /json/getStudentList
[{"studentId":18,"studentName":"小志"},{"studentId":19,"studentName":"小庄"},{"studentId":20,"studentName":"小王"}]-- /json/getStudentMap
{"家庭地址":"厦门市惠安县","学生姓名":{"studentId":25,"studentName":"小王"},"出生年月":202000326}

map 中不管是什么数据类型,都可以转成相应的 json 格式

1.1.4 jackson 中对null的处理

把map中的数据更改,测试jackson 中对null的处理

 @RequestMapping("/getStudentMap")public Map<String,Object> getStudentMap() {Map<String,Object> map = new HashMap();map.put("学生姓名",new Student(25,"小王"));map.put("家庭地址","厦门市惠安县");map.put("出生年月",null);return map;}--/json/getStudentMap 返回结果
{"家庭地址":"厦门市惠安县","学生姓名":{"studentId":25,"studentName":"小王"},"出生年月":null}

添加 jackson 的配置类

package org.example.springbootdemo.config;import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;import java.io.IOException;@Configuration
public class JacksonConfig {@Bean@Primary@ConditionalOnMissingBean(ObjectMapper.class)public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) {ObjectMapper objectMapper = builder.createXmlMapper(false).build();objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() {@Overridepublic void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {jsonGenerator.writeString("");}});return objectMapper;}
}

-----------------------------------------------------结果如下--------------------------------------------------------------

{"家庭地址": "厦门市惠安县","学生姓名": {"studentId": 25,"studentName": "小王"},"出生年月": ""
}

1.2  使用阿里巴巴FastJson的设置

使用 fastJson 时,对 null 的处理和 jackson 有些不同,需要继承 WebMvcConfigurationSupport 类,然后覆盖 configureMessageConverters 方法,在方法中,我们可以选择对要实现 null 转换的场景,配置好即可。

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;@Configuration
public class fastJsonConfig extends WebMvcConfigurationSupport {/*** 使用阿里 FastJson 作为JSON MessageConverter* @param converters*/@Overridepublic void configureMessageConverters(List<HttpMessageConverter<?>> converters) {FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();FastJsonConfig config = new FastJsonConfig();config.setSerializerFeatures(// 保留map空的字段SerializerFeature.WriteMapNullValue,// 将String类型的null转成""SerializerFeature.WriteNullStringAsEmpty,// 将Number类型的null转成0SerializerFeature.WriteNullNumberAsZero,// 将List类型的null转成[]SerializerFeature.WriteNullListAsEmpty,// 将Boolean类型的null转成falseSerializerFeature.WriteNullBooleanAsFalse,// 避免循环引用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);}
}

1.3 封装返回的统一数据结构

1.3.1 定义返回统一的json结构

@Data
public class CommomResult<T> {private String code;private String message;private T data;public CommomResult(String code, String message, T data) {this.code = code;this.message = message;this.data = data;}
}

1.3.2 修改接口层的返回操作及测试

@RestController
@CrossOrigin
@RequestMapping("/json")
public class JsonTest {@RequestMapping("/getStudent")public CommomResult getStudent() {//return new Student(18, "小志");return new CommomResult("0","查询成功",new Student(18,"小志"));}@RequestMapping("/getStudentList")public CommomResult getStudentList() {List<Student> list = new ArrayList<>();list.add(new Student(18, "小志"));list.add(new Student(19, "小庄"));list.add(new Student(20, "小王"));//return list;return new CommomResult<>("0","查询成功",list);}@RequestMapping("/getStudentMap")public CommomResult getStudentMap() {Map<String,Object> map = new HashMap();map.put("学生姓名",new Student(25,"小王"));map.put("家庭地址","厦门市惠安县");map.put("出生年月",null);//return map;return new CommomResult<>("0","查询成功",map);}}

1.3.3 测试结果

-- /json/getStudent
{"code": "0","message": "查询成功","data": {"studentId": 18,"studentName": "小志"}
}-- /json/getStudentList
{"code": "0","message": "查询成功","data": [{"studentId": 18,"studentName": "小志"},{"studentId": 19,"studentName": "小庄"},{"studentId": 20,"studentName": "小王"}]
}-- /json/getStudentMap
{"code": "0","message": "查询成功","data": {"家庭地址": "厦门市惠安县","学生姓名": {"studentId": 25,"studentName": "小王"},"出生年月": ""}
}

2.使用slf4j进行日志记录

3.Spring Boot中的项目属性配置

http://www.dtcms.com/a/284983.html

相关文章:

  • ubuntu 22.02 带外进单用户拯救系统
  • 人工智能之数学基础:概率论和数理统计在机器学习的地位
  • 什么是 M4A 和 WAV?这两种音频互转会导致音质发生变化吗
  • python爬虫入门(小白五分钟从入门到精通)
  • 振石股份闯关上市:业绩连降,资产、负债两端暗藏隐忧
  • leetcode 3202. 找出有效子序列的最大长度 II 中等
  • 18650锂电池点焊机:新能源制造的精密纽带
  • Unreal5从入门到精通之如何实现第一人称和第三人称自由切换
  • 电脑重启后快速找回历史复制内容的实操方法
  • YOLOv8 PTQ、QAT量化及其DepGraph剪枝等压缩与加速推理有效实现(含代码)
  • Leetcode 494. 目标和
  • 力扣 hot100 Day47
  • #systemverilog# 关键字之 protected 用法
  • Python在字符串中查找所有匹配字符索引的多种方法 | Python字符串操作教程
  • h264编码总结
  • C语言(20250717)
  • select_shape_proto 用起来很省事
  • 4G模块 A7680通过MQTT协议连接到华为云
  • 广州VR 内容制作报价:各类 VR 内容的报价详情​
  • 闲庭信步使用图像验证平台加速FPGA的开发:第二十课——图像还原的FPGA实现
  • 深入理解进程等待:wait的简化与waitpid的灵活性
  • kimi故事提示词 + deepseekR1 文生图提示
  • milvus向量数据库连接测试 和 集合维度不同搜索不到内容
  • windows利用wsl安装qemu
  • 利用deepspeed在Trainer下面微调大模型Qwen2.5-3B
  • SpringBoot01-springBoot的特点
  • 登录功能实现深度解析:从会话管理到安全校验全流程指南
  • 【算法训练营Day13】二叉树part3
  • 【中等】题解力扣21:合并两个有序链表
  • 教你使用bge-m3生成稀疏向量和稠密向量