判断一个字符串是否是合法的JSON字符串

判断一个字符串是否是合法的JSON字符串

pom.xml

        <dependency>
            <groupId>com.alibabagroupId>
            <artifactId>fastjsonartifactId>
            <version>1.2.31version>
        dependency>
        <dependency>
            <groupId>com.fasterxml.jackson.coregroupId>
            <artifactId>jackson-databindartifactId>
            <version>2.7.0version>
        dependency>
        <dependency>
            <groupId>com.google.code.gsongroupId>
            <artifactId>gsonartifactId>
            <version>2.5version>
        dependency>

java代码

    /**
     * 暴力解析:Alibaba fastjson
     * @param test
     * @return
     */
    public final static boolean isJSONValid(String test) {
        try {
            JSONObject.parseObject(test);
        } catch (JSONException ex) {
            try {
                JSONObject.parseArray(test);
            } catch (JSONException ex1) {
                return false;
            }
        }
        return true;
    }

    /**
     *  Jackson library
     * @param jsonInString
     * @return
     */
    public final static boolean isJSONValid2(String jsonInString ) {
        try {
            final ObjectMapper mapper = new ObjectMapper();
            mapper.readTree(jsonInString);
            return true;
        } catch (IOException e) {
            return false;
        }
    }

    /**
     * Google Gson
     * @param jsonInString
     * @return
     */
    public final static boolean isJSONValid3(String jsonInString) {
        try {
            gson.fromJson(jsonInString, Object.class);
            return true;
        } catch(JsonSyntaxException ex) {
            return false;
        }
    }

测试结果

isJSONValid() 16510 ms 16161 ms 2018 ms
isJSONValid2() 17946 ms 17486 ms 2698 ms
isJSONValid3() 20648 ms 20208 ms 2508 ms

区别

    /**
     * 是否是合法的Gson字符串
     * @param targetStr
     * @return
     */
    private static boolean isGoodGson(String targetStr,Class clazz) {
        if(StringUtils.isBlank(targetStr)){
            return false;
        }
        try {
            new Gson().fromJson(targetStr,clazz);
            return true;
        } catch(JsonSyntaxException ex) {
            LOG.error("targetStr={} is not a valid {}",targetStr,clazz.getName(),ex);
            return false;
        }
    }

    /**
     * 是否是合法的JsonArray (alibaba 认为前1种不是JSON串)
     * 例如:[{a:b}]  [{'a':'b'}]  [{"a":"b"}]
     * @param targetStr
     * @return
     */
    public static boolean isJsonArray(String targetStr){
      return isGoodGson(targetStr,JsonArray.class);
    }

    /**
     * 是否是合法的JsonObject(alibaba 认为前1种不是JSON串)
     * 例如:{a:b} {'a':'b'} {"a":"b"}
     * @param targetStr
     * @return
     */
    public static boolean isJsonObject(String targetStr){
        return isGoodGson(targetStr,JsonObject.class);
    }

结论

性能相差不太多,推荐方式二isJSONValid2()

参考

stackoverflow

你可能感兴趣的:(常用代码)