JSON (JavaScript Object Notation)一种简单的数据格式,比xml更轻巧。 JSON 是 JavaScript 原生格式,这意味着在 JavaScript 中处理 JSON 数据不需要任何特殊的 API 或工具包。
JSON的规则很简单: 对象是一个无序的“‘名称/值’对”集合。一个对象以“{”(左括号)开始,“}”(右括号)结束。每个“名称”后跟一个“:”(冒号);“‘名称/值’ 对”之间使用“,”(逗号)分隔。具体细节参考http://www.json.org/json-zh.html
举个简单的例子:
function showJSON() { var user = { "username":"andy", "age":20, "info": { "tel": "123456", "cellphone": "98765"}, "address": [ {"city":"beijing","postcode":"222333"}, {"city":"newyork","postcode":"555666"} ] } alert(user.username); alert(user.age); alert(user.info.cellphone); alert(user.address[0].city); alert(user.address[0].postcode); }
同样也可以用JSON来简单的修改数据,修改上面的例子
function showJSON() {
var user =
{
"username":"andy",
"age":20,
"info": { "tel": "123456", "cellphone": "98765"},
"address":
[
{"city":"beijing","postcode":"222333"},
{"city":"newyork","postcode":"555666"}
]
}
alert(user.username);
alert(user.age);
alert(user.info.cellphone);
alert(user.address[0].city);
alert(user.address[0].postcode);
}
这表示一个user对象,拥有username, age, info, address 等属性。
同样也可以用JSON来简单的修改数据,修改上面的例子
function showJSON() {
var user =
{
"username":"andy",
"age":20,
"info": { "tel": "123456", "cellphone": "98765"},
"address":
[
{"city":"beijing","postcode":"222333"},
{"city":"newyork","postcode":"555666"}
]
}
alert(user.username);
alert(user.age);
alert(user.info.cellphone);
alert(user.address[0].city);
alert(user.address[0].postcode);
user.username = "Tom";
alert(user.username);
}
JSON提供了json.js包,下载http://www.json.org/json.js 后,将其引入然后就可以简单的使用object.toJSONString()转换成JSON数据。
function showCar() { var carr = new Car("Dodge", "Coronet R/T", 1968, "yellow"); alert(carr.toJSONString()); } function Car(make, model, year, color) { this.make = make; this.model = model; this.year = year; this.color = color; }
可以使用eval来转换JSON字符到Object
function myEval() { var str = '{ "name": "Violet", "occupation": "character" }'; var obj = eval('(' + str + ')'); alert(obj.toJSONString()); }
或者使用parseJSON()方法
function myEval() { var str = '{ "name": "Violet", "occupation": "character" }'; var obj = str.parseJSON(); alert(obj.toJSONString()); }
下面使用prototype写一个JSON的ajax例子。
先写一个 servlet (我的是servlet.ajax.JSONTest1.java) 就写一句话response.getWriter().print("{ \"name\": \"Violet\", \"occupation\": \"character\" }");
再在页面中写一个ajax的请求
function sendRequest() { var url = "/MyWebApp/JSONTest1"; var mailAjax = new Ajax.Request( url, { method: 'get', onComplete: jsonResponse } ); } function jsonResponse(originalRequest) { alert(originalRequest.responseText); var myobj = originalRequest.responseText.parseJSON(); alert(myobj.name); }
prototype-<st1:chsdate w:st="on" isrocdate="False" islunardate="False" day="30" month="12" year="1899">1.5.1</st1:chsdate>.js中提供了JSON的方法,String.evalJSON(), 可以不使用json.js, 修改上面的方法
function jsonResponse(originalRequest) { alert(originalRequest.responseText); var myobj = originalRequest.responseText.evalJSON(true); alert(myobj.name); }
JSON还提供了java的jar包 http://www.json.org/java/index.html API也很简单,下面举个例子
在javascript中填加请求参数
function sendRequest() { var carr = new Car("Dodge", "Coronet R/T", 1968, "yellow"); var pars = "car=" + carr.toJSONString(); var url = "/MyWebApp/JSONTest1"; var mailAjax = new Ajax.Request( url, { method: 'get', parameters: pars, onComplete: jsonResponse } ); }
使用JSON请求字符串就可以简单的生成JSONObject并进行解析,修改servlet添加JSON的处理(要使用json.jar)
private void doService(HttpServletRequest request, HttpServletResponse response) throws IOException {
String s3 = request.getParameter("car");
try {
JSONObject jsonObj = new JSONObject(s3);
System.out.println(jsonObj.getString("model"));
System.out.println(jsonObj.getInt("year"));
} catch (JSONException e) {
e.printStackTrace();
}
response.getWriter().print("{ \"name\": \"Violet\", \"occupation\": \"character\" }");
}
同样可以使用JSONObject生成JSON字符串,修改servlet
private void doService(HttpServletRequest request, HttpServletResponse response) throws IOException {
String s3 = request.getParameter("car");
try {
JSONObject jsonObj = new JSONObject(s3);
System.out.println(jsonObj.getString("model"));
System.out.println(jsonObj.getInt("year"));
} catch (JSONException e) {
e.printStackTrace();
}
JSONObject resultJSON = new JSONObject();
try {
resultJSON.append("name", "Violet")
.append("occupation", "developer")
.append("age", new Integer(22));
System.out.println(resultJSON.toString());
} catch (JSONException e) {
e.printStackTrace();
}
response.getWriter().print(resultJSON.toString());
}
js 代码
function jsonResponse(originalRequest) { alert(originalRequest.responseText); var myobj = originalRequest.responseText.evalJSON(true); alert(myobj.name); alert(myobj.age); }