1、簡單判斷是否為json格式 ,判斷規則:判斷首尾字母是否為{}或[],如果都不是則不是一個JSON格式的文本。
代碼實作如下:public static boolean getJSONType(String str) {
boolean result = false;
if (StringUtils.isNotBlank(str)) {
str = str.trim();
if (str.startsWith("{") && str.endsWith("}")) {
result = true;
} else if (str.startsWith("[") && str.endsWith("]")) {
result = true;
}
}
return result;
}
2、通過fastjson解析來判斷,解析成功,是json格式;否則,不是json格式
代碼實作如下:public static boolean isJSON2(String str) {
boolean result = false;
try {
Object obj=JSON.parse(str);
result = true;
} catch (Exception e) {
result=false;
}
return result;
}