JSON(JavaScript Object Notation): 是一種輕量級的資料交換格式
一、JSON建構有兩種結構:對象和數組
1、對象:對象在js中表示為“{}”擴起來的內容,資料結構為 {key:value,key:value,...}的索引值對的結構,在物件導向的語言中,key為對象的屬性,value為對應的屬性值,所以很容易理解,取值方法為 對象.key 擷取屬性值,這個屬性值的類型可以是 數字、字串、數組、對象幾種。2、數組:數組在js中是中括弧“[]”擴起來的內容,資料結構為 ["java","javascript","vb",...],取值方式和所有語言中一樣,使用索引擷取,欄位值的類型可以是 數字、字串、數組、對象幾種。經過對象、數組2種結構就可以組合成複雜的資料結構了。
二、具體形式
1、對象
(1)一個對象以“{”(左括弧)開始,“}”(右括弧)結束。
(2)每個“名稱”後跟一個“:”(冒號)(3)“‘名稱/值’ 對”之間使用“,”(逗號)分隔例子:表示人的一個對象:{"姓名" : "大憨","年齡" : 24}
2、數組是值(value)的有序集合。(1)一個數組以“[”(左中括弧)開始,“]”(右中括弧)結束。(2)值之間使用“,”(逗號)分隔。例子:一組學生{"學生" : [{"姓名" : "小明" , "年齡" : 23},{"姓名" : "大憨" , "年齡" : 24}]}說明:此Json對象包括了一個學生數組,而學生數組中的值又是兩個Json對象。
說了這些基本瞭解json的資料結構了...
補充:線上Json校正格式化工具:http://www.bejson.com/go.php?u=http://www.bejson.com/index.php
三、老樣子上次demo
這時我的工程結構圖:上面引用到的外部庫大家網上搜尋下載~
configdata.json:
[ true, false, true]
Address類:
/** * @Title: 建立Address實體類的POJO * @Description: TODO(用一句話描述該檔案做什麼) * @author Potter * @date 2013-2-18 上午10:16:03 * @version V1.0 */public class Address {private String street;//街道private String city;//城市private int zip;//郵編private String tel;//第一個電話號碼private String telTwo;//第二個電話號碼public Address() {}public Address(String street, String city, int zip, String tel, String telTwo){this.street = street;this.city = city;this.zip = zip;this.tel = tel;this.telTwo = telTwo;}public String getStreet() {return street;}public void setStreet(String street) {this.street = street;}public String getCity() {return city;}public void setCity(String city) {this.city = city;}public int getZip() {return zip;}public void setZip(int zip) {this.zip = zip;}public String getTel() {return tel;}public void setTel(String tel) {this.tel = tel;}public String getTelTwo() {return telTwo;}public void setTelTwo(String telTwo) {this.telTwo = telTwo;}}
JsonTest類:
import java.io.File;import java.io.FileNotFoundException;import java.io.FileReader;import java.io.IOException;import java.util.ArrayList;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import net.sf.ezmorph.bean.MorphDynaBean;import net.sf.json.JSONArray;import net.sf.json.JSONFunction;import net.sf.json.JSONObject;public class JsonTest {public static void main(String args[]) {//javaArray和json互相轉換javaArrayAndJsonInterChange();System.out.println("-------------------------------------");//javaList和json互相轉換javaListAndJsonInterChange();System.out.println("-------------------------------------");//javaMpa和Json互轉javaMapAndJsonInterChange();System.out.println("-------------------------------------");//javaObject和jsonObject互轉javaObjectAndJsonInterChange();}/** * javaArray和json互相轉換 */public static void javaArrayAndJsonInterChange() {// java 轉數組boolean[] boolArray = new boolean[] { true, false, true };JSONArray jsonArray = JSONArray.fromObject(boolArray);String s = jsonArray.toString();System.out.println(s);// 通過json擷取數組中的資料String result = readJson("configdata");JSONArray jsonR = JSONArray.fromObject(result);int size = jsonR.size();for (int i = 0; i < size; i++) {System.out.println(jsonR.get(i));}}/** * javaList和json互相轉換 */public static void javaListAndJsonInterChange() {List list = new ArrayList();list.add(new Integer(1));list.add(new Boolean(true));list.add(new Character('j'));list.add(new char[] { 'j', 's', 'o', 'n' });list.add(null);list.add("json");list.add(new String[] { "json", "-", "lib" });// list轉JSONArrayJSONArray jsArr = JSONArray.fromObject(list);System.out.println(jsArr.toString(4));// 從JSON串到JSONArrayjsArr = JSONArray.fromObject(jsArr.toString());// --從JSONArray裡讀取// print: jsonSystem.out.println(((JSONArray) jsArr.get(6)).get(0));}/** * javaMpa和Json互轉 */public static void javaMapAndJsonInterChange() {Map map = new LinkedHashMap();map.put("integer", new Integer(1));map.put("boolean", new Boolean(true));map.put("char", new Character('j'));map.put("charArr", new char[] { 'j', 's', 'o', 'n' });// 注:不能以null為鍵名,否則運行報net.sf.json.JSONException:// java.lang.NullPointerException:// JSON keys must not be null nor the 'null' string.map.put("nullAttr", null);map.put("str", "json");map.put("strArr", new String[] { "json", "-", "lib" });map.put("jsonFunction", new JSONFunction(new String[] { "i" },"alert(i)"));map.put("address", new Address("P.O BOX 54534", "Seattle, WA", 42452,"561-832-3180", "531-133-9098"));// map轉JSONArrayJSONObject jsObj = JSONObject.fromObject(map);System.out.println(jsObj.toString(4));// 從JSON串到JSONObjectjsObj = JSONObject.fromObject(jsObj.toString());//第一種方式:從JSONObject裡讀取// print: jsonSystem.out.println(jsObj.get("str"));// print: address.city = Seattle, WA System.out.println("address.city = " + ((JSONObject) jsObj.get("address")).get("city")); //第二種方式:從動態Bean裡讀取資料,由於不能轉換成具體的Bean,感覺沒有多大用處MorphDynaBean mdBean = (MorphDynaBean) JSONObject.toBean(jsObj);// print: jsonSystem.out.println(mdBean.get("str"));//print: address.city = Seattle, WA System.out.println("address.city = " + ((MorphDynaBean) mdBean.get("address")).get("city")); }/** * javaObject和jsonObject互轉 */public static void javaObjectAndJsonInterChange(){Address address=new Address("P.O BOX 54534", "Seattle, WA", 42452,"561-832-3180", "531-133-9098");//object轉JSONObjectJSONObject jsObj = JSONObject.fromObject(address);System.out.println(jsObj.toString(4));//JsonObject轉java ObjectAddress addressResult=(Address) JSONObject.toBean(jsObj, Address.class);System.out.println("address.city = "+ addressResult.getCity());System.out.println("address.street="+addressResult.getStreet());System.out.println("address.tel = "+ addressResult.getTel());System.out.println("address.telTwo="+addressResult.getTelTwo());System.out.println("address.zip="+addressResult.getZip());}/** * 讀取json檔案 * @param fileName 檔案名稱,不需要尾碼 * @return */public static String readJson(String fileName) {String result = null;try {File myFile = new File("./config/" + fileName + ".json");FileReader fr = new FileReader(myFile);char[] contents = new char[(int) myFile.length()];fr.read(contents, 0, (int) myFile.length());result = new String(contents);fr.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}return result;}}
哈哈~ 沒想到其實挺簡單的!!!
參看文章:
http://jiangzhengjun.iteye.com/blog/463769
http://blog.csdn.net/chenzhehui/article/details/4067482
http://baike.baidu.com/view/136475.htm