SSM框架如何优雅地返回JSON格式数据
在Java Web开发中,SSM(Spring + Spring MVC + MyBatis)框架曾因其分层清晰、灵活高效而被广泛使用。Spring MVC作为表现层框架,提供了强大的JSON数据返回能力,使得前后端分离架构下的数据交互变得简单,本文将详细介绍在SSM框架中如何配置和实现返回JSON格式数据,涵盖环境配置、Controller层编写、常见问题处理及最佳实践。
环境准备:引入JSON依赖
在SSM项目中,返回JSON数据需要依赖JSON处理库,常用的库有Jackson(Spring MVC默认集成)、Gson或Fastjson,以Jackson为例,需在pom.xml中添加以下依赖:
<!-- Jackson核心依赖(Spring MVC已集成,无需额外引入spring-mvc的json转换依赖) -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.13.0</version>
</dependency>
<!-- Jackson注解支持(可选) -->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.13.0</version>
</dependency>
说明:如果使用Spring Boot,
spring-boot-starter-web已默认包含Jackson依赖,无需手动添加。
核心配置:开启Spring MVC注解驱动
Spring MVC通过@ResponseBody注解将Controller方法的返回值序列化为JSON,并直接写入HTTP响应体,要使用该注解,需在Spring MVC配置文件中开启注解驱动(<mvc:annotation-driven/>),该配置会自动注册RequestMappingHandlerAdapter,并装配Jackson的ObjectMapper实例。
Spring MVC配置文件示例(spring-mvc.xml)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 1. 扫描Controller层包 -->
<context:component-scan base-package="com.example.controller"/>
<!-- 2. 开启注解驱动(核心:自动装配@RequestBody和@ResponseBody的处理器) -->
<mvc:annotation-driven/>
<!-- 3. 静态资源处理(可选) -->
<mvc:default-servlet-handler/>
</beans>
关键点:
<mvc:annotation-driven/>会自动注册Jackson2JsonMessageConverter,用于处理JSON序列化和反序列化。
Controller层实现:使用@ResponseBody注解
在Spring MVC中,Controller方法返回JSON数据有两种常用方式:直接在方法上添加@ResponseBody注解,或使用@RestController注解(推荐)。
方式一:@ResponseBody注解(单个方法返回JSON)
@ResponseBody表示方法的返回值直接写入HTTP响应体(而非解析为视图名),Spring MVC会通过Jackson将其序列化为JSON字符串。
示例代码:
import com.example.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.util.ArrayList;
import java.util.List;
@Controller
public class UserController {
/**
* 返回单个对象(JSON格式)
*/
@GetMapping("/user")
@ResponseBody
public User getUser() {
User user = new User(1L, "张三", "zhangsan@example.com");
return user;
}
/**
* 返回List集合(JSON格式)
*/
@GetMapping("/users")
@ResponseBody
public List<User> getUserList() {
List<User> users = new ArrayList<>();
users.add(new User(1L, "张三", "zhangsan@example.com"));
users.add(new User(2L, "李四", "lisi@example.com"));
return users;
}
/**
* 返回简单类型(如String,会被序列化为JSON字符串)
*/
@GetMapping("/message")
@ResponseBody
public String getMessage() {
return "操作成功";
}
}
测试结果:
- 访问
/user,响应体为:{"id":1,"name":"张三","email":"zhangsan@example.com"} - 访问
/users,响应体为:[{"id":1,"name":"张三","email":"zhangsan@example.com"},{"id":2,"name":"李四","email":"lisi@example.com"} - 访问
/message,响应体为:"操作成功"(注意:String会被包裹在双引号中,符合JSON字符串格式)
方式二:@RestController注解(推荐)
如果Controller的所有方法都需要返回JSON,可以直接在类上添加@RestController注解,该注解是@Controller和@ResponseBody的组合,无需在每个方法上重复添加@ResponseBody。
示例代码:
import com.example.entity.User;
import org.springframework.web.bind.annotation.*;
import java.util.HashMap;
import java.util.Map;
@RestController
@RequestMapping("/api")
public class UserControllerWithRest {
/**
* 返回单个对象
*/
@GetMapping("/user/{id}")
public User getUserById(@PathVariable Long id) {
return new User(id, "用户" + id, "user" + id + "@example.com");
}
/**
* 返回Map集合
*/
@PostMapping("/user")
public Map<String, Object> createUser(@RequestBody User user) {
Map<String, Object> result = new HashMap<>();
result.put("code", 200);
result.put("message", "用户创建成功");
result.put("data", user);
return result;
}
}
说明:
@RestController标记的类中,所有方法的返回值都会被@ResponseBody处理,自动序列化为JSON。@RequestBody注解用于将HTTP请求体中的JSON数据反序列化为Java对象(常用于POST/PUT请求)。
进阶配置:自定义JSON序列化
忽略空字段(@JsonInclude)
如果Java对象中有null或空字符串字段,可以通过@JsonInclude注解控制是否序列化到JSON中。
示例:
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.Data;
@Data
@JsonInclude(JsonInclude.Include.NON_NULL) // 忽略null字段
public class User {
private Long id;
private String name;
private String email; // 如果为null,则不会出现在JSON中
}
测试:
若User对象的email为null,返回的JSON为:{"id":1,"name":"张三"}。
自定义日期格式(@JsonFormat)
默认情况下,Date类型会被序列化为时间戳(如1678886400000),可通过@JsonFormat指定格式。
示例:
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import java.util.Date;
@Data
public class Order {
private Long id;
private String orderNo;
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") // 格式化日期
private Date createTime;
}
测试:
返回的JSON中,createTime字段为:"2023-03-15 14:30:00"。
处理循环引用(@JsonIgnore)
在双向关联的对象中(如User和Order互相引用),直接序列化会导致栈溢出(无限循环),可通过@JsonIgnore或@JsonManagedReference/@JsonBackReference解决。
示例:
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
@Data
public class User {
private Long id;
private String name;
@JsonIgnore // 忽略该字段,避免循环引用
private List<Order> orders;
}
@Data
public class Order {
private Long id;
private String orderNo;
private User user; // 双向关联
}
常见问题与解决方案
问题:返回中文乱码
现象:JSON中的中文字段显示为"\u5f20\u4e09"(Unicode编码)。
原因:Spring MVC默认使用ISO-8859-1编码处理响应,而JSON



还没有评论,来说两句吧...