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轉JSONArray
- JSONArray jsArr = JSONArray.fromObject(list);
- System.out.println(jsArr.toString(4));
- // 從JSON串到JSONArray
- jsArr = JSONArray.fromObject(jsArr.toString());
- // --從JSONArray裏讀取
- // print: json
- System.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轉JSONArray
- JSONObject jsObj = JSONObject.fromObject(map);
- System.out.println(jsObj.toString(4));
- // 從JSON串到JSONObject
- jsObj = JSONObject.fromObject(jsObj.toString());
- //第一種方式:從JSONObject裏讀取
- // print: json
- System.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: json
- System.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轉JSONObject
- JSONObject jsObj = JSONObject.fromObject(address);
- System.out.println(jsObj.toString(4));
- //JsonObject轉java Object
- Address 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;
- }
- }