JSON
HTML控制台显示
<script type="text/javascript"> var student = JSON.parse('{"student":"小明","age":"19岁"}'); console.log(student) var user = { user:"小明", age:"19", sex:"男" } console.log(user); /*转换成java字符串 {"student":"小明","age":"19岁"} */ var obj = JSON.stringify(student); console.log(obj) /*转换成字符串 {"user":"小明","age":"19","sex":"男"} */ var s = JSON.stringify(user); console.log(s) /*从字符串转换成json格式*/ var parse = JSON.parse(s); console.log(parse) </script>
jsp 显示JSON
1.通过attribute 只能是jsp,如果是html ,html不支持java代码,不能直接传对象
@WebServlet("/jsonServlet") public class JsonServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Student student = new Student(); student.setId(1); student.setAge(19); student.setName("小明"); req.setAttribute("student",student); req.getRequestDispatcher("/index.jsp").forward(req,resp); }
2.通过 resp 写入json @WebServlet("/jsonServlet") public class JsonServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Student student = new Student(); student.setId(1); student.setAge(19); student.setName("小明"); resp.setContentType("text/html;charset=UTF-8"); resp.setCharacterEncoding("UTF-8"); resp.getWriter().print(new Gson().toJson(student)); }
这个需要google gson-2.5.jar(谷歌)
public class Student { private int id; private String name; private int age; private String sex; private float height; private Date birthday; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public float getHeight() { return height; } public void setHeight(float height) { this.height = height; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", sex='" + sex + '\'' + ", weight=" + height + ", birthday='" + birthday + '\'' + '}'; } }
var heros =JSON.parse('[{"name":"提莫","hp":"1000","cd":"10","op":"11"},{' + '"name":"盖伦","hp":"1000","cd":"10","op":"11"},' + '{"name":"诺手","hp":"1000","cd":"10","op":"11"},' + '{"name":"琴女","hp":"1000","cd":"10","op":"11"},' + '{"name":"布隆","hp":"1000","cd":"10","op":"11"},' + '{"name":"冰女","hp":"1000","cd":"10","op":"11"},' + '{"name":"死歌","hp":"1000","cd":"10","op":"11"}' + ']'); /*获取json数组输出*/ var z=0; for (var i = 0; i <heros.length-1 ; i++) { console.log(heros[i].name,heros[i].hp,heros[i].cd,heros[i].op); console.log(z++); }