两种实现方式:


1、通过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;
}



2、简单判断是否为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;
}

 

第一种方式比较校验比较严格,校验也比较准确。第二种判断比较简单,适合用于约定数据。