博客摘录「 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": "小王"},"出生年月": ""}
}