如何检查给定字符串是否是Java中的有效JSON

如何检查给定字符串是否是Java中的有效JSON

问题描述:

如何在Java中验证JSON字符串?或者我可以使用正则表达式解析它吗?

How do I validate a JSON string in Java? Or could I parse it using regular expressions?

一个疯狂的想法,尝试解析它并捕获异常:

A wild idea, try parsing it and catch the exception:

import org.json.*;

public boolean isJSONValid(String test) {
    try {
        new JSONObject(test);
    } catch (JSONException ex) {
        // edited, to include @Arthur's comment
        // e.g. in case JSONArray is valid as well...
        try {
            new JSONArray(test);
        } catch (JSONException ex1) {
            return false;
        }
    }
    return true;
}

此代码使用 org.json 可在在github上使用的JSON API实现 maven 和部分在Android上

This code uses org.json JSON API implementation that is available on github, in maven and partially on Android.