Home >Java >JavaBase >Java determines whether it is in json format

Java determines whether it is in json format

angryTom
angryTomOriginal
2019-11-18 16:00:333046browse

Java determines whether it is in json format

java determines whether the json format is legal

## Neither the JsonObject nor the JsonArray object can quickly determine whether the json format is legal There is no other way, so we have to use the method of catching exceptions to determine the legality of json.

The code is as follows:

/**
 * 判断是JsonObject
 * @param obj
 * @return
 */
public static boolean isJsonObject(Object obj) {
    String content = obj.toString();
    try {
        JSONObject.parseObject(content);
        if (content.startsWith("{")) {
            return true;
        } else {
            return false;
        }
    } catch (Exception e) {
        return false;
    }
}
/**
 * 判断是JsonArray
 * @param obj
 * @return
 */
public static boolean isJsonArray(Object obj) {
    String content = obj.toString();
    try {
        JSONArray.parseArray(content);
        if (content.startsWith("[")) {
            return true;
        } else {
            return false;
        }
    } catch (Exception e) {
        return false;
    }
}

php Chinese website, a large number of free

Java introductory tutorials, welcome to learn online!

The above is the detailed content of Java determines whether it is in json format. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn