返回JSON数据
1. 在方法上添加@ResponseBody
1.1 不要忘记引入jackson的3个包.
1.2 @ResponseBody使用Jackson进行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 返回值,只能是一个对象,如果是普通数据类型,就不可以。