SpringMVC_day02_3(返回JSON的数组的格式)

                                                                            返回JSON数据
1. 在方法上添加 @ResponseBody
1.1 不要忘记引入jackson的3个包.
1.2 @ResponseBody使用Jackson进行json转换

以前是如何使用JSON格式 传送数据的。
		// 假设从数据库中取出了一些数据
		Student student = new Student();
		student.setSname("刘波");
		student.setSnumber(201502234);
		// 1.设置响应内容的类型
		resp.setContentType("application/json;charset=utf-8");// 设置返回内容的类型 是JSON
		// 2.使用jackson
		ObjectMapper mapper = new ObjectMapper();// 
		String result = mapper.writeValueAsString(student);//将对象转换成 jsonObject形式
		// 3.AJAX响应回页面
		resp.getWriter().print(result);
SpringMvc 如何使用JSON的呢?
@Controller
public class DemoController {
	@RequestMapping("demo.action")
	// 1.设置响应内容类型   
        resp.setContentType("application/json;charset=utf-8")
        // 2.使用jackson把返回值转换成JSON字符串 
	// 3.把返回的字符串放入到响应体中(out.print)
	@ResponseBody
	public People demo(){
		// JSON类型数据作返回值
		People people = new People();
		people.setId(1);
		people.setName("刘波");
		people.setPassword("123456");
		return people;
		
	}
}
在开发的过程中,使用@ResponseBody 似乎好像不用设置 ContentType。
而且在开发中,使用@ResponseBody 返回值,只能是一个对象,如果是普通数据类型,就不可以。





 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值