在JavaWeb的开发过程中对json字符串的解析是比较常见的,那么怎么借助JavaScript去解析json字符串呢?这里直接上代码:
代码一一个 Servlet
package com.ghj.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.google.gson.Gson; public class JsonServlet extends HttpServlet { private static final long serialVersionUID = -699926309344319475L; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/json;charset=utf-8"); PrintWriter out = response.getWriter(); Map<String, List<String>> dataMap = new HashMap<String, List<String>>(); List<String > gradeList = new ArrayList<String>();//年级 gradeList.add("初中一年级"); gradeList.add("初中二年级"); gradeList.add("初中三年级"); dataMap.put("gradeList", gradeList); List<String> courseList = new ArrayList<String>();//课程 courseList.add("语文"); courseList.add("数学"); courseList.add("物理"); dataMap.put("courseList", courseList); out.write(new Gson().toJson(dataMap)); out.flush(); out.close(); } }说明:这里使用了gson-2.2.2.jar包
代码二——一个jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <% String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>首页</title> <script type="text/javascript" src="<%=basePath%>js/jquery-1.7.2.js"></script> <script type="text/javascript"> $(function(){ $("#json").click(function(){ $.ajax({ type: "POST", url: "<%=basePath%>JsonServlet", success: function(data){ var grades = data.gradeList; for(var index in grades){//年级 console.log(grades[index]); } var courses = data.courseList; for(var index in courses){//课程 console.log(courses[index]); } }, error:function(){ alert("数据请求失败!"); } }); }); }); </script> </head> <body> <button id="json">JavaScript解析JSON字符串</button> </body> </html>说明:上面代码没有借助JavaScript中的eval来解析json字符串