java中Array/List/Map/Object與Json互相轉換詳解

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:

[javascript] view plain copy
  1. [  
  2.     true,  
  3.     false,  
  4.     true  
  5. ]  

Address類:

[java] view plain copy
  1. /**    
  2.  * @Title: 創建Address實體類的POJO 
  3.  * @Description: TODO(用一句話描述該文件做什麼) 
  4.  * @author Potter    
  5.  * @date 2013-2-18 上午10:16:03 
  6.  * @version V1.0    
  7.  */  
  8.   
  9. public class Address {  
  10.     private String street;//街道  
  11.     private String city;//城市  
  12.     private int zip;//郵編  
  13.     private String tel;//第一個電話號碼  
  14.     private String telTwo;//第二個電話號碼  
  15.   
  16.     public Address() {  
  17.     }  
  18.   
  19.     public Address(String street, String city, int zip, String tel, String telTwo){  
  20.         this.street = street;  
  21.         this.city = city;  
  22.         this.zip = zip;  
  23.         this.tel = tel;  
  24.         this.telTwo = telTwo;  
  25.     }  
  26.       
  27.     public String getStreet() {  
  28.         return street;  
  29.     }  
  30.   
  31.     public void setStreet(String street) {  
  32.         this.street = street;  
  33.     }  
  34.   
  35.     public String getCity() {  
  36.         return city;  
  37.     }  
  38.   
  39.     public void setCity(String city) {  
  40.         this.city = city;  
  41.     }  
  42.   
  43.     public int getZip() {  
  44.         return zip;  
  45.     }  
  46.   
  47.     public void setZip(int zip) {  
  48.         this.zip = zip;  
  49.     }  
  50.   
  51.     public String getTel() {  
  52.         return tel;  
  53.     }  
  54.   
  55.     public void setTel(String tel) {  
  56.         this.tel = tel;  
  57.     }  
  58.   
  59.     public String getTelTwo() {  
  60.         return telTwo;  
  61.     }  
  62.   
  63.     public void setTelTwo(String telTwo) {  
  64.         this.telTwo = telTwo;  
  65.     }  
  66. }  

 

JsonTest類:

[java] view plain copy
  1. import java.io.File;  
  2. import java.io.FileNotFoundException;  
  3. import java.io.FileReader;  
  4. import java.io.IOException;  
  5. import java.util.ArrayList;  
  6. import java.util.LinkedHashMap;  
  7. import java.util.List;  
  8. import java.util.Map;  
  9.   
  10. import net.sf.ezmorph.bean.MorphDynaBean;  
  11. import net.sf.json.JSONArray;  
  12. import net.sf.json.JSONFunction;  
  13. import net.sf.json.JSONObject;  
  14.   
  15. public class JsonTest {  
  16.   
  17.     public static void main(String args[]) {  
  18.         //javaArray和json互相轉換  
  19.         javaArrayAndJsonInterChange();  
  20.         System.out.println("-------------------------------------");  
  21.         //javaList和json互相轉換  
  22.         javaListAndJsonInterChange();  
  23.         System.out.println("-------------------------------------");  
  24.         //javaMpa和Json互轉  
  25.         javaMapAndJsonInterChange();  
  26.         System.out.println("-------------------------------------");  
  27.         //javaObject和jsonObject互轉  
  28.         javaObjectAndJsonInterChange();  
  29.     }  
  30.   
  31.     /** 
  32.      * javaArray和json互相轉換 
  33.      */  
  34.     public static void javaArrayAndJsonInterChange() {  
  35.         // java 轉數組  
  36.         boolean[] boolArray = new boolean[] { truefalsetrue };  
  37.         JSONArray jsonArray = JSONArray.fromObject(boolArray);  
  38.         String s = jsonArray.toString();  
  39.         System.out.println(s);  
  40.   
  41.         // 通過json獲取數組中的數據  
  42.         String result = readJson("configdata");  
  43.   
  44.         JSONArray jsonR = JSONArray.fromObject(result);  
  45.         int size = jsonR.size();  
  46.         for (int i = 0; i < size; i++) {  
  47.             System.out.println(jsonR.get(i));  
  48.         }  
  49.     }  
  50.   
  51.     /** 
  52.      * javaList和json互相轉換 
  53.      */  
  54.     public static void javaListAndJsonInterChange() {  
  55.         List list = new ArrayList();  
  56.         list.add(new Integer(1));  
  57.         list.add(new Boolean(true));  
  58.         list.add(new Character('j'));  
  59.         list.add(new char[] { 'j''s''o''n' });  
  60.         list.add(null);  
  61.         list.add("json");  
  62.         list.add(new String[] { "json""-""lib" });  
  63.   
  64.         // list轉JSONArray  
  65.         JSONArray jsArr = JSONArray.fromObject(list);  
  66.         System.out.println(jsArr.toString(4));  
  67.   
  68.         // 從JSON串到JSONArray  
  69.         jsArr = JSONArray.fromObject(jsArr.toString());  
  70.         // --從JSONArray裏讀取  
  71.         // print: json  
  72.         System.out.println(((JSONArray) jsArr.get(6)).get(0));  
  73.     }  
  74.   
  75.     /** 
  76.      * javaMpa和Json互轉 
  77.      */  
  78.     public static void javaMapAndJsonInterChange() {  
  79.         Map map = new LinkedHashMap();  
  80.         map.put("integer"new Integer(1));  
  81.         map.put("boolean"new Boolean(true));  
  82.         map.put("char"new Character('j'));  
  83.         map.put("charArr"new char[] { 'j''s''o''n' });  
  84.         // 注:不能以null爲鍵名,否則運行報net.sf.json.JSONException:  
  85.         // java.lang.NullPointerException:  
  86.         // JSON keys must not be null nor the 'null' string.  
  87.         map.put("nullAttr"null);  
  88.   
  89.         map.put("str""json");  
  90.         map.put("strArr"new String[] { "json""-""lib" });  
  91.         map.put("jsonFunction"new JSONFunction(new String[] { "i" },"alert(i)"));  
  92.         map.put("address"new Address("P.O BOX 54534""Seattle, WA"42452,"561-832-3180""531-133-9098"));  
  93.         // map轉JSONArray  
  94.         JSONObject jsObj = JSONObject.fromObject(map);  
  95.         System.out.println(jsObj.toString(4));  
  96.           
  97.         // 從JSON串到JSONObject  
  98.         jsObj = JSONObject.fromObject(jsObj.toString());  
  99.   
  100.         //第一種方式:從JSONObject裏讀取  
  101.         // print: json  
  102.         System.out.println(jsObj.get("str"));  
  103.         // print: address.city = Seattle, WA    
  104.         System.out.println("address.city = " + ((JSONObject) jsObj.get("address")).get("city"));    
  105.   
  106.           
  107.         //第二種方式:從動態Bean裏讀取數據,由於不能轉換成具體的Bean,感覺沒有多大用處  
  108.         MorphDynaBean mdBean = (MorphDynaBean) JSONObject.toBean(jsObj);  
  109.         // print: json  
  110.         System.out.println(mdBean.get("str"));  
  111.         //print: address.city = Seattle, WA    
  112.         System.out.println("address.city = " + ((MorphDynaBean) mdBean.get("address")).get("city"));    
  113.   
  114.     }  
  115.       
  116.     /** 
  117.      * javaObject和jsonObject互轉 
  118.      */  
  119.     public static void  javaObjectAndJsonInterChange(){  
  120.         Address address=new Address("P.O BOX 54534""Seattle, WA"42452,"561-832-3180""531-133-9098");  
  121.         //object轉JSONObject  
  122.         JSONObject jsObj = JSONObject.fromObject(address);  
  123.         System.out.println(jsObj.toString(4));  
  124.           
  125.         //JsonObject轉java Object  
  126.           
  127.         Address addressResult=(Address) JSONObject.toBean(jsObj, Address.class);  
  128.         System.out.println("address.city = "+ addressResult.getCity());  
  129.         System.out.println("address.street="+addressResult.getStreet());  
  130.         System.out.println("address.tel = "+ addressResult.getTel());  
  131.         System.out.println("address.telTwo="+addressResult.getTelTwo());  
  132.         System.out.println("address.zip="+addressResult.getZip());  
  133.     }  
  134.   
  135.     /** 
  136.      * 讀取json文件 
  137.      * @param fileName 文件名,不需要後綴 
  138.      * @return 
  139.      */  
  140.     public static String readJson(String fileName) {  
  141.         String result = null;  
  142.         try {  
  143.             File myFile = new File("./config/" + fileName + ".json");  
  144.             FileReader fr = new FileReader(myFile);  
  145.             char[] contents = new char[(int) myFile.length()];  
  146.             fr.read(contents, 0, (int) myFile.length());  
  147.             result = new String(contents);  
  148.             fr.close();  
  149.         } catch (FileNotFoundException e) {  
  150.             e.printStackTrace();  
  151.         } catch (IOException e) {  
  152.             e.printStackTrace();  
  153.         }  
  154.         return result;  
  155.     }  
  156. }  
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章