1 import net.sf.json.JSONObject; 2 3 public class JsonTools { 4 public static JSONObject getJSONObject(String jData) { 5 if (jData == null || jData.length() <= 0) 6 return null; 7 JSONObject obj = JSONObject.fromObject(jData); 8 return obj; 9 } 10 11 public static <T> String getJsonString(T t) { 12 JSONObject obj = JSONObject.fromObject(t); 13 return obj.toString(); 14 } 15 16 public static String getJsonValueByName(JSONObject object, String name) { 17 if (object == null) 18 return "--"; 19 String value = object.getString(name); 20 if (null == value || "null".equalsIgnoreCase(value)) 21 value = ""; 22 return value; 23 } 24 25 public static String getJsonValueByName(String jData, String name) { 26 if (jData == null || jData.length() <= 0) 27 return ""; 28 JSONObject obj = JSONObject.fromObject(jData); 29 String value = obj.getString(name); 30 if (null == value || "null".equalsIgnoreCase(value)) 31 value = ""; 32 return value; 33 } 34 35 public static String getJsonValueNotNull(String jData, String name) 36 throws Exception { 37 if (jData == null || jData.length() <= 0) 38 throw new Exception("获取请求数据[jsonData]为空"); 39 JSONObject obj = JSONObject.fromObject(jData); 40 String value = obj.getString(name).trim(); 41 if (null == value || value.length() <= 0) 42 throw new Exception("获取的数据对象[" + name + "]为空"); 43 return value; 44 } 45 46 @SuppressWarnings({ "rawtypes", "unchecked" }) 47 public static <T> T getJavaBean(String jData, Class clazz) { 48 49 JSONObject jsonObject = JSONObject.fromObject(jData); 50 return (T) JSONObject.toBean(jsonObject, clazz); 51 } 52 }