進(jìn)行JSON和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的解釋器])
- 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)換成JSON
- 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()));
- //將JSON轉(zhuǎn)換成XML
- 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();
- }
- }
- }
- }
JSON和XML是一種有用的、輕量級協(xié)議,現(xiàn)在可用于 PHP V5.2,它可以輕松地實現(xiàn)從 PHP 應(yīng)用程序中提取出數(shù)據(jù),并將其放入 Ajax 應(yīng)用程序的過程。相應(yīng)地,PHP 中的 JSON 同樣也是輕量級且十分有用的,只包含兩個易于使用的函數(shù)。使用這些函數(shù),我們可以轉(zhuǎn)換和導(dǎo)出對象結(jié)構(gòu),還可以使用 json_encode() 使來自 PHP 數(shù)據(jù)庫連接的數(shù)據(jù)可用于 Ajax 應(yīng)用程序。
在 Ajax 應(yīng)用程序中處理完數(shù)據(jù)后,可以將數(shù)據(jù)返回 PHP 腳本并用 json_decode() 重新創(chuàng)建可用的對象數(shù)據(jù)結(jié)構(gòu)。當(dāng)把數(shù)據(jù)返回到 PHP 后,我們可以將其存儲到數(shù)據(jù)庫中,或使用JSON和XML提供的眾多選擇中的任何其他數(shù)據(jù)處理方法。