JSON

网友投稿 637 2022-11-23

jsON

JSON

HTML控制台显示

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

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:String 根据 第一个逗号去掉逗好后面的内容
下一篇:基于Graphics2D drawImage图片失真的解决方案
相关文章

 发表评论

暂时没有评论,来抢沙发吧~