学而实习之 不亦乐乎

Java:Gson 检测字符串是否为有效的 JSON 串

2022-08-02 07:47:10

开发中有时候需要检查 JSON 字符串是否有效,如何方便快速地进行检测呢?


方法一:通过构造 JsonObject

public static boolean isJson(String Json) {
    Gson gson = new Gson();
    try {
        gson.fromJson(Json, Object.class);
        return true;
    } catch (com.google.gson.JsonSyntaxException ex) {
        return false;
    }
}

或者

public static boolean isJson(String Json) {
    try {
        new JSONObject(Json);
    } catch (JSONException ex) {
        try {
            new JSONArray(Json);
        } catch (JSONException ex1) {
            return false;
        }
    }
    return true;
}

方法二:使用 JsonParser 的 parseString() 方法

JsonParser.parseString(respJson).isJsonObject();