其實在 http://www.json.org/ 中有詳細的說明各種語言間交換的標準.
此文主要是紀錄怎樣從伺服接受 Client 端 upload 的 JSON 在不使用 Request 的情況下.
這裡使用 Js 端的 lib [superbutton link=”https://github.com/douglascrockford/JSON-js” title=”” image=”” class=”sprbtn_orange” target=”_blank” rel=””]JSON.js[/superbutton]
以及 Java 端的 lib [superbutton link=”http://www.json.org/java/index.html” title=”JAVAObject” image=”” class=”sprbtn_yellow” target=”” rel=””]JAVAObject.java[/superbutton]
[js]
var xmlHttp;
function createXMLHttpRequest() {
if (window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} else if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}
}
function doJSON() {
var car = getCarObject();
// Use the JSON JavaScript library to stringify the Car object
var carAsJSON = JSON.stringify(car);
alert(" Car object as JSON:n " + carAsJSON);
var url = " JSONExample?timeStamp= " + new Date().getTime();
createXMLHttpRequest();
xmlHttp.open("POST", url, true);
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlHttp.send(carAsJSON);
}
function handleStateChange() {
if (xmlHttp.readyState == 4) {
if (xmlHttp.status == 200) {
parseResults();
}
}
}
function parseResults() {
var responseDiv = document.getElementById("serverResponse");
if (responseDiv.hasChildNodes()) {
responseDiv.removeChild(responseDiv.childNodes[0]);
}
var responseText = document.createTextNode(xmlHttp.responseText);
responseDiv.appendChild(responseText);
}
function getCarObject() {
return new Car("Dodge", "Coronet R/T", 1968, "yellow");
}
function Car(make, model, year, color) {
this.make = make;
this.model = model;
this.year = year;
this.color = color;
}
[/js]
以上可見 JSON 其實並不需要從正常的 POST/GET 方式上傳到伺服, 只需要使用 XMLHTTPRequest.send(carAsJSON); 直接丟上 server 即可, 於 JAVA 的 Lib [superbutton link=”http://www.json.org/java/index.html” title=”JAVAObject” image=”” target=”” rel=””]JAVAObject.java[/superbutton] 則會直接從 http header 中讀取 JSON 字串, 再還原為可讀取的 Object 物件
[java]
package ajaxbook.chap3;
import java.io.*;
import java.net.*;
import java.text.ParseException;
import javax.servlet.*;
import javax.servlet.http.*;
import org.json.JSONObject; // JAVAObject.java Library
public class JSONExample extends HttpServlet
{
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
String json = readJSONStringFromRequestBody(request);
// Use the JSON-Java binding library to create a JSON object in Java
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();
}
}
[/java]
就個人而言, 坊間使用的 Action?MyVar={“abc”:”xxxxx”} 等上傳方式需然可行,
但終於需要額外訂立一個 MyVar 於合作Project中不建議使用.