标签:
在网页中想后台传递多个数据时,有时数据还是多个动态列表,数据很复杂时,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 }
从json数组中得到相应java数组,如果要获取java数组中的元素,只需要遍历该数组。
1 /** 2 * 从json数组中得到相应java数组 3 * JSONArray下的toArray()方法的使用 4 * @param str 5 * @return 6 */ 7 public static Object[] getJsonToArray(String str) { 8 JSONArray jsonArray = JSONArray.fromObject(str); 9 return jsonArray.toArray(); 10 } 11 12 public static void main(String[] args) { 13 JSONArray jsonStrs = new JSONArray(); 14 jsonStrs.add(0, "cat"); 15 jsonStrs.add(1, "dog"); 16 jsonStrs.add(2, "bird"); 17 jsonStrs.add(3, "duck"); 18 19 Object[] obj=getJsonToArray(jsonStrs.toString()); 20 for(int i=0;i<obj.length;i++){ 21 System.out.println(obj[i]); 22 } 23 }
从json数组中得到java数组,可以对该数组进行转化,如将JSONArray转化为String型、Long型、Double型、Integer型、Date型等等。
分别采用jsonArray下的getString(index)、getLong(index)、getDouble(index)、getInt(index)等方法。
同样,如果要获取java数组中的元素,只需要遍历该数组。
1 /** 2 * 将json数组转化为Long型 3 * @param str 4 * @return 5 */ 6 public static Long[] getJsonToLongArray(String str) { 7 JSONArray jsonArray = JSONArray.fromObject(str); 8 Long[] arr=new Long[jsonArray.size()]; 9 for(int i=0;i<jsonArray.size();i++){ 10 arr[i]=jsonArray.getLong(i); 11 System.out.println(arr[i]); 12 } 13 return arr; 14 } 15 /** 16 * 将json数组转化为String型 17 * @param str 18 * @return 19 */ 20 public static String[] getJsonToStringArray(String str) { 21 JSONArray jsonArray = JSONArray.fromObject(str); 22 String[] arr=new String[jsonArray.size()]; 23 for(int i=0;i<jsonArray.size();i++){ 24 arr[i]=jsonArray.getString(i); 25 System.out.println(arr[i]); 26 } 27 return arr; 28 } 29 /** 30 * 将json数组转化为Double型 31 * @param str 32 * @return 33 */ 34 public static Double[] getJsonToDoubleArray(String str) { 35 JSONArray jsonArray = JSONArray.fromObject(str); 36 Double[] arr=new Double[jsonArray.size()]; 37 for(int i=0;i<jsonArray.size();i++){ 38 arr[i]=jsonArray.getDouble(i); 39 } 40 return arr; 41 } 42 /** 43 * 将json数组转化为Date型 44 * @param str 45 * @return 46 */ 47 public static Date[] getJsonToDateArray(String jsonString) { 48 49 JSONArray jsonArray = JSONArray.fromObject(jsonString); 50 Date[] dateArray = new Date[jsonArray.size()]; 51 String dateString; 52 Date date; 53 SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd"); 54 for (int i = 0; i < jsonArray.size(); i++) { 55 dateString = jsonArray.getString(i); 56 try { 57 date=sdf.parse(dateString); 58 dateArray[i] = date; 59 } catch (Exception e) { 60 e.printStackTrace(); 61 } 62 } 63 return dateArray; 64 } 65 66 67 public static void main(String[] args) { 68 69 JSONArray jsonLongs = new JSONArray(); 70 jsonLongs.add(0, "111"); 71 jsonLongs.add(1, "222.25"); 72 jsonLongs.add(2, new Long(333)); 73 jsonLongs.add(3, 444); 74 75 Long[] log=getJsonToLongArray(jsonLongs.toString()); 76 for(int i=0;i<log.length;i++){ 77 System.out.println(log[i]); 78 } 79 80 JSONArray jsonStrs = new JSONArray(); 81 jsonStrs.add(0, "2011-01-01"); 82 jsonStrs.add(1, "2011-01-03"); 83 jsonStrs.add(2, "2011-01-04 11:11:11"); 84 85 Date[] d=getJsonToDateArray(jsonStrs.toString()); 86 for(int i=0;i<d.length;i++){ 87 System.out.println(d[i]); 88 } 89 } 90 /*结果如下: 91 * 111 92 * 222 93 * 333 94 * 444 95 * 96 * Sat Jan 01 00:00:00 CST 2011 97 * Mon Jan 03 00:00:00 CST 2011 98 * Tue Jan 04 00:00:00 CST 2011 99 */
/**
* java转为json对象
* @author wudouzhu
*/
public class JsonTest3 {
public static void main(String[] args) {
SimInfo s = new SimInfo();
s.setAddTime("2000-10-21");
s.setIccid("23");
s.setId("243432435435365789");
s.setImei("423");
s.setImsi("545");
s.setPhoneType("1878789887");
s.setRemark("1");
s.setTel("0518-666678");
String json = new JSONArray().fromObject(s).toString();
System.out.println("json:"+json);
//json:[{"addTime":"2000-10-21","iccid":"23","id":"243432435435365789","imei":"423","imsi":"545","phoneType":"1878789887","remark":"1","tel":"0518-666678"}]
}
}
/**
* json转为java对象
* @author wudouzhu
*/
public class JsonTest {
public static void main(String[] args) {
String json="[{\"addTime\":\"2011-09-19 14:23:02\",\"iccid\":\"1111\",\"id\":0,\"imei\":\"2222\",\"imsi\":\"3333\",\"phoneType\":\"4444\",\"remark\":\"aaaa\",\"tel\":\"5555\"}]";
if(json.indexOf("[")!=-1){
json = json.replace("[","");
}
if(json.indexOf("]")!=-1){
json = json.replace("]","");
}
JSONObject object = JSONObject.fromObject(json);
SimInfo simInfo = (SimInfo)JSONObject.toBean(object,SimInfo.class);
System.out.println("obj:"+object);
System.out.println(simInfo.getAddTime());
System.out.println(simInfo.getIccid());
System.out.println(simInfo.getId());
System.out.println(simInfo.getImei());
System.out.println(simInfo.getImsi());
System.out.println(simInfo.getPhoneType());
System.out.println(simInfo.getRemark());
System.out.println(simInfo.getTel());
}
}
/**
* json转为java集合对象
* @author wudouzhu
*/
public class JsonTest2 {
public static void main(String[] args) {
JsonTest2 t = new JsonTest2();
String jsons="[{\"addTime\":\"2011-09-19 14:23:02\",\"iccid\":\"1111\",\"id\":0,\"imei\":\"2222\",\"imsi\":\"3333\",\"phoneType\":\"4444\",\"remark\":\"aaaa\",\"tel\":\"5555\"}," +
"{\"addTime\":\"2011-11-11 14:23:02\",\"iccid\":\"2222\",\"id\":0,\"imei\":\"2222\",\"imsi\":\"3333\",\"phoneType\":\"4444\",\"remark\":\"aaaa\",\"tel\":\"5555\"}]";
List<SimInfo> simInfos = t.getJavaCollection(new SimInfo(),jsons);
System.out.println("size:"+simInfos.size());
for(SimInfo s:simInfos){
System.out.println("addTime:"+s.getAddTime());
System.out.println("==========");
}
}
/*
* 封装将json对象转为java集合对象
*/
private <T> List<T> getJavaCollection(T clazz,String jsons){
List<T> objs = null;
JSONArray jsonArray = (JSONArray)JSONSerializer.toJSON(jsons);
if(jsonArray!=null){
objs = new ArrayList<T>();
List list = (List)JSONSerializer.toJava(jsonArray);
for(Object o:list){
JSONObject jsonObject = JSONObject.fromObject(o);
T obj = (T)JSONObject.toBean(jsonObject,clazz.getClass());
objs.add(obj);
}
}
return objs;
}
}
标签:
原文地址:http://www.cnblogs.com/doudouxiaoye/p/5692274.html