☆JSON介紹
JSON(JavaScript Object Notation) 是一種輕量級的數(shù)據(jù)交換格式。易于人閱讀和編寫。同時也易于機器解析和生成。(官方網(wǎng)站http://www.json.org)
☆JSON語法
JSON的語法很簡單,就是使用大括號'{}',中括號'[]',逗號',',冒號':',雙引號'“”'。數(shù)據(jù)類型:嵌套對象、數(shù)組、字符串、數(shù)字、布爾值或空值(來自官方網(wǎng)站http://www.json.org/json-zh.html)
1)對象是一個無序的“‘名稱/值’對”集合。一個對象以“{”(左括號)開始,“}”(右括號)結(jié)束。每個“名稱”后跟一個“:”(冒號);“‘名稱/值’ 對”之間使用“,”(逗號)分隔。
2)數(shù)組是值(value)的有序集合。一個數(shù)組以“[”(左中括號)開始,“]”(右中括號)結(jié)束。值之間使用“,”(逗號)分隔。
3)值(value)可以是雙引號括起來的字符串(string)、數(shù)值(number)、true、false、 null、對象(object)或者數(shù)組(array)。這些結(jié)構(gòu)可以嵌套。
4)字符串(string)是由雙引號包圍的任意數(shù)量Unicode字符的集合,使用反斜線轉(zhuǎn)義。一個字符(character)即一個單獨的字符串(character string)。 字符串(string)與C或者Java的字符串非常相似。
5)數(shù)值(number)也與C或者Java的數(shù)值非常相似。除去未曾使用的八進制與十六進制格式。除去一些編碼細節(jié)。
☆JSON優(yōu)勢
1)簡潔明了,操作方便(對比XML)
JSON和XML都是基于文本的,兩者都使用Unicode編碼。JSON和XML都很容易閱讀。主觀上,JSON更清晰,冗余更少。XML適合標(biāo)記文檔(配置文件),JSON更適合數(shù)據(jù)交換。
☆JSON操作
1)JSON字符串轉(zhuǎn)換成JAVAScript對象(調(diào)用eval()[JSON本來就是JS的一個子集,所以可以使用JS的解釋器])
- <script>
- var my_json='{"FBI":[{"name":"rose","age":"25"},{"name":"jack","age":"25"}],"NBA":[{"name":"tom","sex":"man"},{"name":"jack","sex":"women"}]}';
- var my_object=eval('('+my_json+')');
- document.writeln(my_object.FBI[1].name);
- </script>
<script>var my_json='{"FBI":[{"name":"rose","age":"25"},{"name":"jack","age":"25"}],"NBA":[{"name":"tom","sex":"man"},{"name":"jack","sex":"women"}]}';var my_object=eval('('+my_json+')');document.writeln(my_object.FBI[1].name);</script>
-
- 上面的代碼也可省略屬性的雙引號,如下
- <script>
- var my_json='{FBI:[{name:"rose",age:"25"},{name:"jack",age:"25"}],NBA:[{name:"tom",sex:"man"},{name:"jack",sex:"women"}]}';
- var my_object=eval('('+my_json+')');
- document.writeln(my_object.FBI[1].name);
- </script>
上面的代碼也可省略屬性的雙引號,如下<script>var my_json='{FBI:[{name:"rose",age:"25"},{name:"jack",age:"25"}],NBA:[{name:"tom",sex:"man"},{name:"jack",sex:"women"}]}';var my_object=eval('('+my_json+')');document.writeln(my_object.FBI[1].name);</script>
2)將JS對象轉(zhuǎn)換成JSON字符串(調(diào)用toJSONString,需要下載json.js[http://www.json.org/json.js])
- <script src="json.js"></script>
- <script>
- var my_object={
- FBI:[
- {name:"rose",age:"25"},
- {name:"jack",age:"25"}
- ],
- NBA:[
- {name:"tom",sex:"man"},
- {name:"jack",sex:"women"}
- ]
- };
- document.writeln(my_object.toJSONString());
- </script>
<script src="json.js"></script><script>var my_object={FBI:[{name:"rose",age:"25"},{name:"jack",age:"25"}],NBA:[{name:"tom",sex:"man"},{name:"jack",sex:"women"}]};document.writeln(my_object.toJSONString());</script>
3)XML與JSON轉(zhuǎn)換(需要下載json.org提供的JAVA類,json.zip[http://www.json.org/java/json.zip]),代碼如下: JAVA實現(xiàn)XML與JSON之間的轉(zhuǎn)換
- package woxingwosu;
-
- import java.io.BufferedReader;
- import java.io.BufferedWriter;
- import java.io.FileReader;
- import java.io.FileWriter;
-
- import org.json.JSONObject;
- import org.json.XML;
-
- public class XMl2JSON {
-
-
- public static void main(String[] args) {
- BufferedReader buffRed=null;
- BufferedWriter buffWri=null;
- try{
-
- String fileName1="woxingwosu.xml";
- buffRed=new BufferedReader(new FileReader(fileName1));
- String tempStr;
- StringBuffer xmlStrBuff=new StringBuffer();
- while((tempStr=buffRed.readLine())!=null)
- xmlStrBuff.append(tempStr);
- System.out.println("JSON str="+XML.toJSONObject(xmlStrBuff.toString()));
-
-
- String jsonStr="{Heros:{FBI:[{name:\"rose\",age:\"25\"},{name:\"jack\",age:\"25\"}],NBA:[{name:\"tom\",sex:\"man\"},{name:\"jack\",sex:\"women\"}]}};";
- String fileName2="myxml.xml";
- buffWri=new BufferedWriter(new FileWriter(fileName2));
- JSONObject jsonObj=new JSONObject(jsonStr);
- buffWri.write("<?xml version=\"1.0\" encoding=\"GBK\"?>");
- buffWri.newLine();
- buffWri.write("<!DOCTYPE properties SYSTEM \"http://java.sun.com/dtd/properties.dtd\">");
- buffWri.newLine();
- buffWri.write(XML.toString(jsonObj));
- buffWri.flush();
-
- System.out.println("run end!");
- }catch(Exception e){
- e.printStackTrace();
- }finally{
- try{
- if(buffRed!=null)
- buffRed.close();
- if(buffWri!=null)
- buffWri.close();
- }catch(Exception e){
- e.printStackTrace();
- }
- }
- }
- }
package woxingwosu;import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.FileReader;import java.io.FileWriter;import org.json.JSONObject;import org.json.XML;public class XMl2JSON {public static void main(String[] args) {BufferedReader buffRed=null;BufferedWriter buffWri=null;try{//將XML轉(zhuǎn)換成JSONString fileName1="woxingwosu.xml";buffRed=new BufferedReader(new FileReader(fileName1));String tempStr;StringBuffer xmlStrBuff=new StringBuffer();while((tempStr=buffRed.readLine())!=null)xmlStrBuff.append(tempStr);System.out.println("JSON str="+XML.toJSONObject(xmlStrBuff.toString()));//將JSON轉(zhuǎn)換成XMLString jsonStr="{Heros:{FBI:[{name:\"rose\",age:\"25\"},{name:\"jack\",age:\"25\"}],NBA:[{name:\"tom\",sex:\"man\"},{name:\"jack\",sex:\"women\"}]}};";String fileName2="myxml.xml";buffWri=new BufferedWriter(new FileWriter(fileName2));JSONObject jsonObj=new JSONObject(jsonStr);buffWri.write("<?xml version=\"1.0\" encoding=\"GBK\"?>");buffWri.newLine();buffWri.write("<!DOCTYPE properties SYSTEM \"http://java.sun.com/dtd/properties.dtd\">");buffWri.newLine();buffWri.write(XML.toString(jsonObj));buffWri.flush();System.out.println("run end!");}catch(Exception e){e.printStackTrace();}finally{try{if(buffRed!=null)buffRed.close();if(buffWri!=null)buffWri.close();}catch(Exception e){e.printStackTrace();}}}}
woxingwosu.xml
- <?xml version="1.0" encoding="GBK"?>
- <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
- <properties>
- <entry key="no">woxingwosu</entry>
- <entry key="name">我行我素</entry>
- </properties> 輸出結(jié)果: xml2json結(jié)果
- JSON str={"properties":{"entry":[{"key":"no","content":"woxingwosu"},{"key":"name","content":"我行我素"}]}}json2xml結(jié)果
- <?xml version="1.0" encoding="GBK"?>
- <!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
- <Heros><NBA><sex>man</sex><name>tom</name></NBA><NBA><sex>women</sex><name>jack</name></NBA><FBI><age>25</age><name>rose</name></FBI><FBI><age>25</age><name>jack</name></FBI></Heros>
<?xml version="1.0" encoding="GBK"?><!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"><properties><entry key="no">woxingwosu</entry><entry key="name">我行我素</entry></properties> 輸出結(jié)果: xml2json結(jié)果JSON str={"properties":{"entry":[{"key":"no","content":"woxingwosu"},{"key":"name","content":"我行我素"}]}}json2xml結(jié)果<?xml version="1.0" encoding="GBK"?><!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd"><Heros><NBA><sex>man</sex><name>tom</name></NBA><NBA><sex>women</sex><name>jack</name></NBA><FBI><age>25</age><name>rose</name></FBI><FBI><age>25</age><name>jack</name></FBI></Heros>
4)AJAX中運用JSON(比使用DOM解析XML簡單) 一個在AJAX中運用JSON的簡單例子
在響應(yīng)的程序中輸入返回的值:
out.println("{FBI:[{name:\"rose\",age:\"25\"},{name:\"jack\",age:\"25\"}],NBA:[{name:\"tom\",sex:\"man\"},{name:\"jack\",sex:\"women\"}]}");
在頁面上(點確定頁面上會顯示jack)
- <script language="javascript" src="js/prototype.js"></script>
- <input type="button" onclick="loadInfo()" value="確定"/>
- <script>
- function loadInfo(){
- new Ajax.Request("hello",{
- onComplete:function(req){
- var res=eval("("+req.responseText+")");
- $('mydiv').innerHTML=res.FBI[1].name;
- }
- }
- );
- }
- </script>
- <div id="mydiv"></div>
<script language="javascript" src="js/prototype.js"></script><input type="button" onclick="loadInfo()" value="確定"/><script>function loadInfo(){new Ajax.Request("hello",{onComplete:function(req){var res=eval("("+req.responseText+")");$('mydiv').innerHTML=res.FBI[1].name;}});}</script><div id="mydiv"></div>
4)Java中運用Json(需要下載json的java開發(fā)包) Java中運用Json
- package callCenterServer;
-
- import java.util.ArrayList;
- import org.json.JSONArray;
- import org.json.JSONObject;
-
-
- public class Test {
-
-
-
-
- public static void main(String[] args) throws Exception{
- ArrayList<Area> areas=new ArrayList<Area>();
- areas.add(new Test.Area("福建","福州"));
- areas.add(new Test.Area("福建","廈門"));
- areas.add(new Test.Area("福建","泉州"));
- areas.add(new Test.Area("四川","成都"));
- areas.add(new Test.Area("四川","攀枝花"));
- JSONObject jsonObject=new JSONObject();
- for(Test.Area area:areas){
- if(jsonObject.has(area.province)){
- JSONArray jsonArray=(JSONArray)jsonObject.get(area.province);
- jsonArray.put(area.city);
- }else{
- JSONArray jsonArray=new JSONArray();
- jsonArray.put(area.city);
- jsonObject.put(area.province, jsonArray);
- }
- }
- System.out.println(jsonObject);
- }
-
- static class Area{
- private final String province;
- private final String city;
- Area(String province,String city){
- this.province=province;
- this.city=city;
- }
- }
-
- }