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 }