您的位置:首页 > 编程语言 > Java开发

SpringMVC处理JSON

2016-03-02 09:53 363 查看
springmvc处理json可谓是方便到没有朋友。

springmvc处理json步骤

在搭建好的springmvc框架里面导入jackson系列jar包

在@Controller类中书写对应的测试处理json的方法

除了用@RequestMapping注解修饰测试方法,还需要用springmvc内核中的@ResponseBody来修饰方法

测试方法不再返回String或者ModelAndView,而是返回List或者Colletion集合数据

最后在动态页面上测试 通过get链接方式测试方法,而后可以利用ajax来获取json数组

导入jar包

![导入jackson jar包](http://img.blog.csdn.net/20160302093125959)

jackson jar包的主要作用是将对象数据转换为json数据。

写测试方法

@Controller
public class SpringMVCTest {
@Autowired
private UserInfoDao userInfoDao;

@RequestMapping("/hello")
public String hello() {
return "success";
}

@ResponseBody
@RequestMapping("/testJson")
public List<User> testJson(){
return userInfoDao.getAll();
}

}


@Repository
public class UserInfoDao {
private List<User> users = new ArrayList<User>();

public UserInfoDao() {

users.add(new User("Tom", 20, "4738588", "Seattle"));
users.add(new User("Jerry", 21, "4735528", "Seattle"));
users.add(new User("Bob", 19, "4738568", "New York"));
users.add(new User("Harry", 22, "5678548", "London"));
}

public List<User> getAll() {
return users;
}
}


在这里,我们模拟数据库新建了一些User对象数据,而且我们在testJson方法中将这些List数据集合返回,testJson方法除了用@RequestMapping方法修饰,还用@ResponseBody注解修饰,这样springmvc会利用前面的jackson jar包还有自己的核心功能将这些List集合数据转为json数组。

页面上写对应测试的链接以及ajax接受json数组

<%@ 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>HandleJSON</title>
<script type="text/javascript"
src="${pageContext.request.contextPath}/scripts/jquery-1.7.2.js"></script>
<script type="text/javascript">
$(function() {
$("#testJson").click(function() {
var url = this.href;
var args = {};
$.get(url, args, function(data) {
for (var i = 0; i < data.length; i++)
alert(data[i].username);
});

return false;
});

});
</script>
</head>
<body>
<a href="hello"> hello world</a>
<br>
<a href="testJson" id="testJson">Test JSON</a>

</body>
</html>


利用get方式来测试testJson方法,在这里利用ajax来发送get请求以及得到json数组数据,当点击Test JSON链接的时候页面不会跳转,因为jquert已经将a链接默认行为改为return false; 页面会弹出对象的username信息,我们直接用data[i].username,得到json部分信息。json数组完整信息可以用浏览器开发工具直接看到。
![这里写图片描述](http://img.blog.csdn.net/20160302095000327)

其次 ,我们不用ajax来处理发送请求处理json,点击Test JSON 可以在新的页面上看到json数组信息。
![这里写图片描述](http://img.blog.csdn.net/20160302095136678)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: