JAVA解析JSON數據


在網頁中想后台傳遞多個數據時,有時數據還是多個動態列表,數據很復雜時,JavaScript程序員喜歡把他們作為json串進行處理,后台收到后需要對json字符串進行解析,幸好有JSON-lib,這個Java類包用於把bean,map和XML轉換成JSON並能夠把JSON轉回成bean和DynaBean。
下載地址:http://json-lib.sourceforge.net/

  1 public class Test {
  2 
  3 /**
  4 
  5 * @param args
  6 
  7 * @author wen
  8 
  9 */
 10 
 11 public static void main(String[] args) {
 12 
 13 //            test1();
 14 
 15 //            test2();
 16 
 17 String json = “{1:{1:{jhinfo:['計划一','親親寶寶','www.wenhq.com'],jhrate:['1-5:10.0','6-100:5.0/1']},2:{jhinfo:['計划二','親親寶寶','www.wenhq.com'],jhrate:['1-100:100.0']},3:{jhinfo:['計划三','親親寶寶','www.wenhq.com'],jhrate:['1-100:150.0/7']}},2:{4:{jhinfo:['年計划','親親寶寶','www.wenhq.com'],jhrate:['365-365:1000.0']}}}”;
 18 
 19 try {
 20 
 21 JSONObject jsonObject = JSONObject.fromObject(json);
 22 
 23 String name = jsonObject.getString(“1″);
 24 
 25 String address = jsonObject.getString(“2″);
 26 
 27 System.out.println(“name is:” + name);
 28 
 29 System.out.println(“address is:” + address);
 30 
 31 Iterator it=jsonObject.keys();
 32 
 33 while (it.hasNext()){
 34 
 35 System.out.println(jsonObject.get(it.next()));
 36 
 37 }
 38 
 39 } catch (JSONException e) {
 40 
 41 e.printStackTrace();
 42 
 43 }
 44 
 45 }
 46 
 47 /**
 48 
 49 * json對象字符串轉換
 50 
 51 * @author wen
 52 
 53 */
 54 
 55 private static void test2() {
 56 
 57 String json = “{‘name’: ‘親親寶寶’,'array’:[{'a':'111','b':'222','c':'333'},{},{'a':'999'}],’address’:'親親寶寶’}”;
 58 
 59 try {
 60 
 61 JSONObject jsonObject = JSONObject.fromObject(json);
 62 
 63 String name = jsonObject.getString(“name”);
 64 
 65 String address = jsonObject.getString(“address”);
 66 
 67 System.out.println(“name is:” + name);
 68 
 69 System.out.println(“address is:” + address);
 70 
 71 JSONArray jsonArray = jsonObject.getJSONArray(“array”);
 72 
 73 for (int i = 0; i < jsonArray.size(); i++) {
 74 
 75 System.out.println(“item ” + i + ” :” + jsonArray.getString(i));
 76 
 77 }
 78 
 79 } catch (JSONException e) {
 80 
 81 e.printStackTrace();
 82 
 83 }
 84 
 85 }
 86 
 87 /**
 88 
 89 * json數組 轉換,數組以[開頭
 90 
 91 * @author wen
 92 
 93 */
 94 
 95 private static void test1() {
 96 
 97 boolean[] boolArray = new boolean[]{true,false,true};
 98 
 99 JSONArray jsonArray1 = JSONArray.fromObject( boolArray );
100 
101 System.out.println( jsonArray1 );
102 
103 // prints [true,false,true]
104 
105 List list = new ArrayList();
106 
107 list.add( “first” );
108 
109 list.add( “second” );
110 
111 JSONArray jsonArray2 = JSONArray.fromObject( list );
112 
113 System.out.println( jsonArray2 );
114 
115 // prints ["first","second"]
116 
117 JSONArray jsonArray3 = JSONArray.fromObject( “['json','is','easy']” );
118 
119 System.out.println( jsonArray3 );
120 
121 // prints ["json","is","easy"]
122 
123 }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM