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

引入依赖:


            com.alibaba
            fastjson
            1.2.31
        
        
            com.fasterxml.jackson.core
            jackson-databind
            2.7.0
        
        
            com.google.code.gson
            gson
            2.5
        
/**
     * 暴力解析: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;
        }
    }

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

你可能感兴趣的:(如何判断一个字符串是否是合法的JSON字符串)