如果是linux系统,还可以通过调用linux的jq(需要安装)来检测
echo '{"name":"czz","gender":"M","age":25}' | jq .
该命令解析json
如果字符串不合法,将会解析失败:
如果java开发,可以用json相关插件,但经测试gson的fromJson,解析普通字符串如"abc",也可以解析成功,故不推荐使用gson
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.version}</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
代码如下:
package com.XXX.util;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.sun.org.apache.xpath.internal.operations.Bool;
import java.io.IOException;
/**
* Created by czz on 2020/1/13.
*/
public class JsonUtils {
public static Boolean jsonValidByJackson(String jsonStr){
try {
final ObjectMapper mapper = new ObjectMapper();
mapper.readTree(jsonStr);
return true;
} catch (IOException e) {
return false;
}
}
public static Boolean jsonValidByFastjson(String jsonStr){
try {
JSONObject.parseObject(jsonStr);
} catch (Exception e) {
try {
JSONObject.parseArray(jsonStr);
} catch (JSONException ex) {
return false;
}
}
return true;
}
public static Boolean jsonValidByGson(String jsonStr){
Gson gson = new Gson();
try {
gson.fromJson(jsonStr, Object.class);
return true;
} catch(JsonSyntaxException e) {
return false;
}
}
public static void main(String[] args) {
String jsonObj = "{\"name\":\"czz\",\"gender\":\"M\",\"age\":25}";
String jsonListStr = "[\"yyy\",\"UUU\",\"iii\"]";
String jsonListObj = "[{\"name\":\"czz\",\"gender\":\"M\",\"age\":25},{\"name\":\"aaa\",\"gender\":\"F\",\"age\":20}]";
String jsonObjWithList = "{\"name\":\"depart\",\"epp\":[{\"name\":\"czz\",\"gender\":\"M\",\"age\":25},{\"name\":\"aaa\",\"gender\":\"F\",\"age\":20}]}";
String jsonError = "{\"name:\"czz\",\"gender\":\"M\",\"age\":25}";
String str = "test测试";
Boolean b1 = jsonValidByJackson(str);
Boolean b2 = jsonValidByFastjson(str);
Boolean b3 = jsonValidByGson(str);
System.out.println("b1:"+b1);
System.out.println("b2:"+b2);
System.out.println("b3:"+b3);
}
}
以上方法仅供参考,欢迎大家在评论区补充!
希望可以帮助到大家,大家也可关注我的公众号方便在手机上进行查看