页面:jsonExample.jsp
<%@ page cOntentType="text/html; charset=GBK" %>
服务器:JSONExample.java
package ajaxbook.chap4;
import java.io.*;
import java.net.*;
import java.text.ParseException;
import javax.servlet.*;
import javax.servlet.http.*;
import org.json.JSONObject;
public class JSONExample
extends HttpServlet {
//处理Post方法
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException,
IOException {
String json =
readJSONStringFromRequestBody(request);
//使用JSON绑字Ajax对象
JSONObject jsOnObject= null;
try {
jsOnObject= new
JSONObject(json);
}
catch (ParseException pe) {
System.out.println("ParseException:
" + pe.toString());
}
//返回输出结果
String respOnseText= "You have a " +
jsonObject.getInt("year") + " "
+
jsonObject.getString("make") + " " +
jsonObject.getString("model")
+ " " + " that is " +
jsonObject.getString("color") + " in color.";
response.setContentType("text/xml");
response.getWriter().print(responseText);
}
//得到参数
private String
readJSONStringFromRequestBody(HttpServletRequest request) {
StringBuffer json = new StringBuffer();
String line = null;
try {
BufferedReader reader =
request.getReader();
while ( (line = reader.readLine())
!= null) {
json.append(line);
}
}
catch (Exception e) {
System.out.println("Error reading
JSON string: " + e.toString());
}
return json.toString();
}
}
注意:要引入json.js和json的源文件,使用json.jar不行,源文件参见书籍源代码第三章