2019独角兽企业重金招聘Python工程师标准>>>
两种实现方式:
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;
}
第一种方式比较校验比较严格,校验也比较准确。第二种判断比较简单,适合用于约定数据。
转载于:https://my.oschina.net/u/182501/blog/1529315
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)