public class UserInfo { private String name; private Integer age; public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
@Controller public class json { @RequestMapping("/tojson") public void write(HttpServletRequest request, HttpServletResponse response) throws IOException { List<UserInfo> list=new ArrayList<UserInfo>(); UserInfo u1=new UserInfo(); u1.setName("啊啊"); u1.setAge(22); UserInfo u2=new UserInfo(); u2.setName("哈哈"); u2.setAge(20); list.add(u1); list.add(u2); String re= JSON.toJSONString(list); response.getWriter().write(re); } }
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <script type="text/javascript" src="${pageContext.request.contextPath}/js/jquery-1.12.4.js"></script> <script type="text/javascript"> $(function () { $.ajax({ url:"${pageContext.request.contextPath}/tojson", type:"post", data:{}, success:function (data) { alert(data); } }); }); </script> <body> <h2>流氓</h2> </body> </html>