1 import org.json.JSONException; 2 import org.json.JSONObject; 3 import org.dom4j.DocumentException; 4 import org.dom4j.DocumentHelper; 5 6 public class StringTest { 7 8 /** 9 * @param args 10 */ 11 public static void main(String[] args) { 12 String string1 = "123"; 13 String string2 = "fdgsewe323"; 14 String string3 = "{/"task/":/"324vfsdfg/"}"; 15 String string4 = "<ww>3243</ww>"; 16 // System.out.println("string1::number"+isNumber(string1)); 17 // System.out.println("string2::number"+isNumber(string2)); 18 // System.out.println("string3::json"+isJson(string3)); 19 // System.out.println("string4::xml"+isXML(string4)); 20 // System.out.println("string1::json"+isJson(string1)); 21 // System.out.println("string2::xml"+isXML(string2)); 22 // System.out.println("string3::number"+isNumber(string3)); 23 // System.out.println("string4::xml"+isXML(string4)); 24 25 System.out.println("string1::"+getType(string1)); 26 System.out.println("string2::"+getType(string2)); 27 System.out.println("string3::"+getType(string3)); 28 System.out.println("string4::"+getType(string4)); 29 } 30 31 public static String getType(String string) { 32 if (isNumber(string)) 33 return "Number"; 34 else if (isJson(string)) 35 return "Json"; 36 else if (isXML(string)) 37 return "xml"; 38 else 39 return "String"; 40 } 41 42 43 /** 44 * 判断字符串是否是数字 45 */ 46 public static boolean isNumber(String value) { 47 return isInteger(value) || isDouble(value); 48 } 49 50 /** 51 * 判断字符串是否是整数 52 */ 53 public static boolean isInteger(String value) { 54 try { 55 Integer.parseInt(value); 56 return true; 57 } catch (NumberFormatException e) { 58 return false; 59 } 60 } 61 62 /** 63 * 判断字符串是否是浮点数 64 */ 65 public static boolean isDouble(String value) { 66 try { 67 Double.parseDouble(value); 68 if (value.contains(".")) 69 return true; 70 return false; 71 } catch (NumberFormatException e) { 72 return false; 73 } 74 } 75 76 /** 77 * 判断是否是json结构 78 */ 79 public static boolean isJson(String value) { 80 try { 81 new JSONObject(value); 82 } catch (JSONException e) { 83 return false; 84 } 85 return true; 86 } 87 88 /** 89 * 判断是否是xml结构 90 */ 91 public static boolean isXML(String value) { 92 try { 93 DocumentHelper.parseText(value); 94 } catch (DocumentException e) { 95 return false; 96 } 97 return true; 98 } 99 }