Java调用webservice时用到了json格式的数据,然后就整理这个类。那里不合适的话,希望能够得到指正。
1 public class JsonsAndBeanList 2 { 3 /** 4 * json数据转换为对象数据 5 * @param jsonObject 6 * @param cla 7 * @return 8 */ 9 public static <T> T convertToObj(JSONObject jsonObject, Class<T> cla) 10 { 11 if (jsonObject == null) 12 { 13 return null; 14 } 15 Field[] fb = cla.getDeclaredFields(); 16 T t; 17 try 18 { 19 t = cla.newInstance(); 20 for (int j = 0; j < fb.length; j++) 21 { 22 String fieldName = fb[j].getName(); 23 String fieldNameU = fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); 24 Method method = cla.getMethod("set" + fieldNameU, fb[j].getType()); 25 method.invoke(t, jsonObject.get(fieldName)); 26 } 27 return t; 28 29 } catch (Exception e) 30 { 31 e.printStackTrace(); 32 } 33 return null; 34 } 35 36 /** 37 * json数据转换为数据集合 38 * @param strJson 39 * @param cla 40 * @return 41 */ 42 public static <T> List<T> convertToList(String strJson, Class<T> cla) 43 { 44 JSONArray jsonArray = null; 45 try 46 { 47 jsonArray = new JSONArray(strJson); 48 } catch (JSONException e1) 49 { 50 e1.printStackTrace(); 51 } 52 List<T> list = new ArrayList<T>(); 53 if (jsonArray == null) 54 { 55 return list; 56 } 57 try 58 { 59 for (int i = 0; i < jsonArray.length(); i++) 60 { 61 JSONObject jsonObject = jsonArray.getJSONObject(i); 62 T t = convertToObj(jsonObject, cla); 63 list.add(t); 64 } 65 } catch (Exception e) 66 { 67 e.printStackTrace(); 68 } 69 return list; 70 } 71 72 /** 73 * 对象数据转换为json数据 74 * @param cla 75 * @return 76 */ 77 public static <T> String convertToJson(T cla) 78 { 79 if (cla == null) 80 { 81 return null; 82 } 83 Field[] fb = cla.getClass().getDeclaredFields(); 84 String t = "{"; 85 try 86 { 87 for (int j = 0; j < fb.length; j++) 88 { 89 String fieldName = fb[j].getName(); 90 String fieldNameU = 91 fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1); 92 Method method = cla.getClass().getMethod("get" + fieldNameU); 93 t += "\"" + fieldName + "\":\"" + method.invoke(cla).toString() + "\","; 94 } 95 t = t.substring(0, t.length() - 1) + "}"; 96 return t; 97 98 } catch (Exception e) 99 { 100 e.printStackTrace(); 101 } 102 return null; 103 } 104 105 /** 106 * 数据集合转换为json格式 107 * @param list 108 * @return 109 */ 110 public static <T> String convertToJsons(List<T> list) 111 { 112 String result = "["; 113 if (list == null) 114 { 115 return null; 116 } 117 for (int i = 0; i < list.size(); i++) 118 { 119 result += convertToJson(list.get(i)) + ","; 120 } 121 result = result.substring(0, result.length() - 1) + "]"; 122 return result; 123 } 124 }
方法返回值前的"<T>"是说明函数内会用到泛型类"T"。
参数中出现"<T>"的话,就说明这个参数类型不固定,你想传什么传什么(当然这个"什么"也是有限制的,就不详述了)。