SpringMVC教程之如何处理JSON

一、前言

SpringMVC如何将数据处理成JSON返回,总结起来有三个步骤:

  • 加入jar包
  • 编写目标方法,使其返回 JSON 对应的对象或集合
  • 在方法上添加 @ResponseBody 注解

下面我们通过代码编写相应的实现过程。

二、案例

♦pom.xml中加入依赖的jar包

<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-core</artifactId>
	<version>2.2.2</version>
</dependency>
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-databind</artifactId>
	<version>2.2.2</version>
</dependency>
<dependency>
	<groupId>com.fasterxml.jackson.core</groupId>
	<artifactId>jackson-annotations</artifactId>
	<version>2.2.2</version>
</dependency>

♦编写User类

public class User {
	private Integer id;
	// 用户名
	@NotBlank(message = "名字不能为空")
	private String userName;
	// 密码
	@NotBlank(message = "密码不能为空")
	private String password;
	// 邮箱
	@NotBlank(message = "邮箱不能为空")
	@Email(message = "邮箱格式错误")
	private String email;
	// 年龄
	@NotNull(message = "年龄不能为空")
	@Max(value = 120, message = "年龄最大不能超过120")
	private Integer age;
	// 雇佣日期
	@NotNull(message = "雇佣日期不能为空")
	@DateTimeFormat(pattern = "yyyy-MM-dd")
        @JsonFormat(pattern = "yyyy-MM-dd")
	private Date hireTime;

	public User() {
	}

	public User(Integer id, String userName, String password, String email,
			Integer age, Date hireTime) {
		this.id = id;
		this.userName = userName;
		this.password = password;
		this.email = email;
		this.age = age;
		this.hireTime = hireTime;
	}

	public Date getHireTime() {
		return hireTime;
	}

	public void setHireTime(Date hireTime) {
		this.hireTime = hireTime;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", userName=" + userName + ", password="
				+ password + ", email=" + email + ", age=" + age
				+ ", hireTime=" + hireTime + "]";
	}
}

注意:使用@JsonFormat(pattern = “yyyy-MM-dd”)将JSON中时间格式化输出

♦编写控制器处理类UserHandler

@RequestMapping("/user")
@Controller
public class UserHandler {
@RequestMapping(value = "/listAllUser")
	@ResponseBody
	public List<User> listAllUser() {
		List<User> list = new ArrayList<User>();
                //模拟数据库取出的数据
		list.add(new User(1, "Queen", "123", "queen@163.com", 27, new Date()));
		list.add(new User(1, "King", "321", "king@163.com", 44, new Date()));
		return list;
	}
}

或者这样写也可以实现返回JSON数据

@RequestMapping("/user")
@Controller
public class UserHandler {
@RequestMapping(value = "/listAllUser")
	public ResponseEntity<List<User>> listAllUser() {
		List<User> list = new ArrayList<User>();
		list.add(new User(1, "Queen", "123", "queen@163.com", 27, new Date()));
		list.add(new User(1, "King", "321", "king@163.com", 44, new Date()));
		return new ResponseEntity<List<User>>(list, HttpStatus.OK);
	}
}

♦编写userList.html列表界面

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>用户列表</title>
    <link rel="stylesheet" type="text/css" href="/js/jquery-easyui-1.4.1/themes/default/easyui.css">
    <link rel="stylesheet" type="text/css" href="/js/jquery-easyui-1.4.1/themes/icon.css">
    <script type="text/javascript" src="/js/jquery-easyui-1.4.1/jquery-1.9.1.min.js"></script>
    <script type="text/javascript" src="/js/jquery-easyui-1.4.1/jquery.easyui.min.js"></script>
    <script type="text/javascript" src="/js/jquery-easyui-1.4.1/locale/easyui-lang-zh_CN.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#roleList').datagrid({
                title: '',
                loadMsg: "数据加载中,请稍后……",
                nowrap: false,
                striped: true,
                collapsible: true,
                url: '/user/listAllUser',
                pageList: [10, 15, 20, 25, 30, 40, 50],
                pageSize: 15,
                sortName: 'hireTime',
                sortOrder: 'desc',
                remoteSort: false,
                width :500,
                columns: [[
                    { field: 'userName', title: '用户名', width: 100, align: 'center', sortable: true },
                    { field: 'email', title: '邮箱', width: 120, align: 'center', sortable: true },
                    { field: 'age', title: '年龄', width: 100, align: 'center', sortable: true},
                    { field: 'hireTime', title: '雇佣时间', width: 100, align: 'center', sortable: true}
                ]],
                rownumbers: true
            });
        });
    </script>
</head>
<body>
    <table id="roleList"></table>
</body>
</html>

♦运行测试效果如下

SpringMVC教程之如何处理JSON的照片 - 1

至此,我们关于SpringMVC教程之如何处理JSON介绍完毕。想要了解更多关于SpringMVC开发的教程,请参考http://www.marsitman.com/springmvc
博客地址:http://www.marsitman.com/springmvc/springmvc-dealjson.html
版权声明:本文为博主原创文章,允许转载,但转载必须标明出处。

 

 

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!



点赞

发表评论

电子邮件地址不会被公开。 必填项已用*标注