贴一个案例代码,便于日后翻阅
服务器代码:JsonServlet.java
package com.dhh; import java.io.IOException; import java.io.PrintWriter; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONArray; import net.sf.json.JsonConfig; public class JsonServlet extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException { doPost(request,response); } protected void doPost(HttpServletRequest request,IOException { request.setCharacterEncoding("utf-8"); response.setContentType("text/xml;charset=utf-8"); PrintWriter out = response.getWriter(); //1、json格式测试: //标准格式:[{stuid:'1',stuname:'张三'},{stuid:'2',stuname:'李四'},{stuid:'3',stuname:'王五'},//{stuid:'5',stuname:'赵六'},{stuid:'6',stuname:'邓八'},{stuid:'7',stuname:'陈九'}] List<Student> stuLists = new ArrayList<Student>(); stuLists.add(new Student(001,"张三",20,"打球1")); stuLists.add(new Student(002,"李四",30,"打球2")); stuLists.add(new Student(003,"王五",40,"打球3")); stuLists.add(new Student(005,"赵六",50,"打球4")); stuLists.add(new Student(006,"邓八",60,"打球5")); stuLists.add(new Student(007,"陈九",70,"打球6")); //手动遍历ArrayList,拼凑成json对象,只封装了stuid,stuname字段 // StringBuffer buffer = new StringBuffer("["); // for(int i = 0 ;i< stuLists.size(); i++){ // Student student = stuLists.get(i); // buffer.append('{'); // buffer.append("stuid"); // buffer.append(":'"); // buffer.append(student.getStuid()); // buffer.append("',"); // buffer.append("stuname"); // buffer.append(":'"); // buffer.append(student.getStuname()); // buffer.append("'"); // buffer.append("}"); // buffer.append(','); // } // buffer.deleteCharAt(buffer.length()-1); // buffer.append("]"); // // System.out.println("拼凑出来的结果:"+buffer.toString()); // out.println(buffer.toString()); //通过第三方工具类来封装json //封装所有的字段 //JSONArray array = JSONArray.fromObject(stuLists); //或者根据业务需求,不用某些字段 JsonConfig config = new JsonConfig(); //排除封装age,hobby 字段 config.setExcludes(new String[]{"age","hobby"}); JSONArray array = JSONArray.fromObject(stuLists,config); System.out.println(array.toString()); out.println(array.toString()); //json简单测试 // out.print("[{id:20,name:'dhh'},{id:30,name:你懂的}]"); // //2、xml格式测试 // out.println("<china>"); // out.println("<province name='湖南'>"); // out.println("<city>长沙</city>"); // out.println("<city>岳阳</city>"); // out.println("<city>湘潭</city>"); // out.println("<city>永州</city>"); // out.println("</province>"); // // out.println("<province name='辽宁'>"); // out.println("<city>沈阳</city>"); // out.println("<city>鞍山</city>"); // out.println("<city>大连</city>"); // out.println("<city>营口</city>"); // out.println("</province>"); // out.println("</china>"); } }
HTML代码:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <Meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Json测试</title> <script type="text/javascript"> function ajaxFunction(){ var xmlHttp; try{ // Firefox,Opera 8.0+,Safari xmlHttp=new XMLHttpRequest(); } catch (e){ try{// Internet Explorer xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); } catch (e){ try{ xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); } catch (e){} } } return xmlHttp; } window.onload=function(){ //创建xmlHttpRequest对象 var xmlReq = ajaxFunction(); //创建服务器监听器 xmlReq.onreadystatechange = function(){ if(xmlReq.readyState==4){ if(xmlReq.status==200) { //1、json数据测试 var jsonData = xmlReq.responseText; alert("我的数据:"+jsonData); //注意:将字符串转换为对象 var jsonObj = eval("("+jsonData+")"); //是一个数组类型的json数据 alert(jsonObj[4].stuname); //2、xml格式数据测试 // var provinceXML = xmlReq.responseXML; // //得到city字段 // var provinces = provinceXML.getElementsByTagName("city"); // alert(provinces.length); } } } xmlReq.open("post","../JsonServlet?timeStamp="+new Date().getTime(),true); xmlReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded"); xmlReq.send(null); } </script> </head> <body> </body> </html>原文链接:https://www.f2er.com/ajax/164738.html