json 详解
以前只知道有json,并不知道能有什么用途,今天就仔细的了解了下……
浏览器从服务器端接收数据时,那些数据必须以浏览器能够理解的格式来发送,服务器端的编程语言只能以如下3种格式返回数据:xml、json、html
JSON:JavaScript 对象表示法(JavaScript Object Notation), 是存储和交换文本信息的语法。一种轻量级的数据交换格式,类似 XML,比 XML 更小、更快,更易解析。Json是javascript的原生格式,这意味着在javascript中处理json数据不需要任何特殊的api或工具包。
相比 XML 的不同之处:没有结束标签,更短,读写的速度更快,能够使用内建的 JavaScript eval() 方法进行解析,使用数组不使用保留字
为什么使用 JSON?
对于 AJAX 应用程序来说,JSON 比 XML 更快更易使用:
使用 XML、读取 XML 文档、使用 XML DOM 来循环遍历文档、读取值并存储在变量中
使用 JSON、读取 JSON 字符串、用 eval() 处理 JSON 字符串
Json规则很简单:
a.映射用冒号 “:” 表示,名称:值
b.并列的数据之间用逗号(,)分隔。名称1:值1,名称2:值2
c.映射的集合(对象)用大括号(“{}”)表示。{名称1:值1,名称2:值2}
d.并列数据的集合(数组)用方括号(”[]”)表示。
[
{名称1:值1,名称2:值2},
{名称1:值1,名称2:值2}
]
e. 元素值可具有的类型:string,number,object,array,true,false,null
Json只是一种文本字符串,被存储在responseText属性中,为了读取存储在responseText属性中的json数据,需要根据js中的eval函数把字符串当作它的参数,然后这个字符串会被当做js代码来执行,因为json的字符串就是由js代码构成的,所以它本身是可执行的,eval通过计算 string 得到的值(如果有的话)
下面是例子:
客户端:
[html]
<body>
<script type="text/javascript">
<%--
// json表示形式如此强大,几乎可以满足任何常用服务器语言的需求
//js表示一个对象用json
var people={"name":"ljf","age":"20","email":"ljfbest@foxmail.com"};
//多个对象
var people1=[
{"name":"ljf","age":"20","email":"ljfbest@foxmail.com"},
{"name":"ljf1","age":"21","email":"ljfbest1@foxmail.com"}
]
//混搭
var peoples={"param1":
[
{"name":"ljf","age":"20","email":"ljfbest@foxmail.com"},
{"name":"ljf1","age":"21","email":"ljfbest1@foxmail.com"}
],
"param2":
[
{"no":"123","class":"2"},
{"name":"ljf1","age":"21","email":"ljfbest1@foxmail.com"}
]
}
var information={
"name":"ljfbest",
"age":"20",
"tel":"155555555",
address:[
{"family":"shangqiu","code":"123333"},
{"company":"nyist","code":"1222333"}
]
}//名称不带引号也可以,此例中的address
alert(information.address[0].family);
--%>
function ajaxFunction(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest();
}catch(e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP")
}catch(e){}
}
}
return xmlHttp;
}
window.onload=function(){
document.getElementById("ok").onclick= function()//与服务器交互监听返回的数据状态
{
var xmlReq=ajaxFunction();
xmlReq.onreadystatechange=function(){
if(xmlReq.readyState==4){
if(xmlReq.status==200||xmlReq.status==304)
var data=xmlReq.responseText;
alert(data);//此时服务器返回的只是字符串 "{pid:1,pname:'河南'}"
var dataObj=eval("("+data+")");//此时被转化为json obj,注意要在两边加()
alert(dataObj[1].pname);//dataObj: Object pid: 1 pname: "河南"
for(var i=0;i<dataObj.length;i++)
alert(dataObj[i].pname);
}
}
//post方法请求,服务器端用post接受,
xmlReq.open("post","/test/JsonServlet?cache="+new Date(),true);
xmlReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlReq.send(null);
}
}
</script>
<select id="province" name="province">
<option value="">
请选择...
</option>
</select>
<button id="ok">提交</button>
</body>
<body>
<script type="text/javascript">
<%--
// json表示形式如此强大,几乎可以满足任何常用服务器语言的需求
//js表示一个对象用json
var people={"name":"ljf","age":"20","email":"ljfbest@foxmail.com"};
//多个对象
var people1=[
{"name":"ljf","age":"20","email":"ljfbest@foxmail.com"},
{"name":"ljf1","age":"21","email":"ljfbest1@foxmail.com"}
]
//混搭
var peoples={"param1":
[
{"name":"ljf","age":"20","email":"ljfbest@foxmail.com"},
{"name":"ljf1","age":"21","email":"ljfbest1@foxmail.com"}
],
"param2":
[
{"no":"123","class":"2"},
{"name":"ljf1","age":"21","email":"ljfbest1@foxmail.com"}
]
}
var information={
"name":"ljfbest",
"age":"20",
"tel":"155555555",
address:[
{"family":"shangqiu","code":"123333"},
{"company":"nyist","code":"1222333"}
]
}//名称不带引号也可以,此例中的address
alert(information.address[0].family);
--%>
function ajaxFunction(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest();
}catch(e){
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}catch(e){
try{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP")
}catch(e){}
}
}
return xmlHttp;
}
window.onload=function(){
document.getElementById("ok").onclick= function()//与服务器交互监听返回的数据状态
{
var xmlReq=ajaxFunction();
xmlReq.onreadystatechange=function(){
if(xmlReq.readyState==4){
if(xmlReq.status==200||xmlReq.status==304)
var data=xmlReq.responseText;
alert(data);//此时服务器返回的只是字符串 "{pid:1,pname:'河南'}"
var dataObj=eval("("+data+")");//此时被转化为json obj,注意要在两边加()
alert(dataObj[1].pname);//dataObj: Object pid: 1 pname: "河南"
for(var i=0;i<dataObj.length;i++)
alert(dataObj[i].pname);
}
}
//post方法请求,服务器端用post接受,
xmlReq.open("post","/test/JsonServlet?cache="+new Date(),true);
xmlReq.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlReq.send(null);
}
}
</script>
<select id="province" name="province">
<option value="">
请选择...
</option>
</select>
<button id="ok">提交</button>
</body>
服务器端:
[java]
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
/***********************************************************
String str="{pid:1,pname:'河南'}";
***********************************************************/
String str="[{pid:1,pname:'商丘'},{pid:2,pname:'郑州'},{pid:3,pname:'安阳'}]";
out.print(str);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter out=response.getWriter();
/***********************************************************
String str="{pid:1,pname:'河南'}";
***********************************************************/
String str="[{pid:1,pname:'商丘'},{pid:2,pname:'郑州'},{pid:3,pname:'安阳'}]";
out.print(str);
}
在java中经常牵扯到一系列对象,对象很多,要拼成一个json对象,很麻烦,下面的例子把province 写成一个类,用第三方类库json(http://json-lib.sourceforge.net/),需要用到的jar包:json-lib-2.4-jdk15.jar、commons-lang 2.5、 commons-beanutils 1.8.0、commons-collections 3.2.1、commons-logging 1.1.1、ezmorph 1.0.6
[java]
public class Province {
private int id;
private String pname;
public Province(int id, String pname) {
super();
this.id = id;
this.pname = pname;
}
//省略getter,setter……
}
public class Province {
private int id;
private String pname;
public Province(int id, String pname) {
super();
this.id = id;
this.pname = pname;
}
//省略getter,setter……
}
[java]
public class JsonServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/******************************集合转化为json对象*********************/
List<Province> list=new ArrayList<Province>();
Province p1=new Province(1, "商丘");
Province p2=new Province(2, "鄭州");
Province p3=new Province(3, "安陽");
list.add(p1);
list.add(p2);
list.add(p3);
//JSONArray jsonArray=JSONArray.fromObject(list);//json_lib
//System.out.println(jsonArray);//[{"id":1,"pname":"商丘"},{"id":1,"pname":"鄭州"},{"id":1,"pname":"安陽"}]
//屏蔽掉某些不想要的属性
JsonConfig config=new JsonConfig();
config.setExcludes(new String[]{"id"});
JSONArray jsonArray=JSONArray.fromObject(list,config);
System.out.println(jsonArray);//[{"pname":"商丘"},{"pname":"鄭州"},{"pname":"安陽"}]
/****************************对象转化为json对象*********************/
Province p=new Province(4,"洛阳");
JSONObject jsonObject=JSONObject.fromObject(p);
System.out.println(jsonObject);
}
public class JsonServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
/******************************集合转化为json对象*********************/
List<Province> list=new ArrayList<Province>();
Province p1=new Province(1, "商丘");
Province p2=new Province(2, "鄭州");
Province p3=new Province(3, "安陽");
list.add(p1);
list.add(p2);
list.add(p3);
//JSONArray jsonArray=JSONArray.fromObject(list);//json_lib
//System.out.println(jsonArray);//[{"id":1,"pname":"商丘"},{"id":1,"pname":"鄭州"},{"id":1,"pname":"安陽"}]
//屏蔽掉某些不想要的属性
JsonConfig config=new JsonConfig();
config.setExcludes(new String[]{"id"});
JSONArray jsonArray=JSONArray.fromObject(list,config);
System.out.println(jsonArray);//[{"pname":"商丘"},{"pname":"鄭州"},{"pname":"安陽"}]
/****************************对象转化为json对象*********************/
Province p=new Province(4,"洛阳");
JSONObject jsonObject=JSONObject.fromObject(p);
System.out.println(jsonObject);
}