Java 中可靠的 JSON 字符串验证器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15791878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 20:52:44  来源:igfitidea点击:

Reliable JSON string validator in Java

javajson

提问by rich

I need some help coming with a reliable JSON string validator - a method which intake a string and checks if it's a valid JSON. Example: if I pass {"color":"red"}or {"amount":15}it will pass but something like "My invalid json"will not. In short I need something that is as reliable as www.jsonlint.com validator. BTW - I'm not interested in deserializing into java object, because that's not my requirement. I may receive an arbitrary string and all I have to do is validate it has a valid JSON format.

我需要一些可靠的 JSON 字符串验证器的帮助——一种接收字符串并检查它是否是有效 JSON 的方法。示例:如果我通过{"color":"red"}{"amount":15}它会通过但类似的东西"My invalid json"不会。简而言之,我需要像 www.jsonlint.com 验证器一样可靠的东西。顺便说一句 - 我对反序列化为 java 对象不感兴趣,因为这不是我的要求。我可能会收到一个任意字符串,我所要做的就是验证它是否具有有效的 JSON 格式。

I have already researched on this forum several posts on the subject regarding java JSON string validations.

我已经在这个论坛上研究了几篇关于 java JSON 字符串验证的主题的帖子。

What I have done so far:

到目前为止我做了什么:

I tried using these classes: org.json.JSONObjectand org.json.JSONArrayin the following manner:

我尝试使用这些类:org.json.JSONObjectorg.json.JSONArray以下列方式:

private static boolean isValidJSONStringObject(String requestBody){
    try {
        new JSONObject(requestBody);
    } catch (JSONException jsonEx) {
        return false;
    }
    return true;
}

private static boolean isValidJSONStringArray(String requestBody) {
    try {
        new JSONArray(requestBody);
    } catch (JSONException jsonEx) {
        return false;
    }
    return true;
}

However, the following strings (entire lines) still go through, and they shouldn't:

但是,以下字符串(整行)仍然通过,它们不应该:

{"color":"red"}{"var":"value"}

[1,2,3][true,false]

in other words when I have objects/arrays repeated w/out any encapsulation in some parent object. If you paste these lines in www.jsonlint.com validator they both fail.

换句话说,当我在某些父对象中重复使用对象/数组而没有任何封装时。如果您将这些行粘贴到 www.jsonlint.com 验证器中,它们都会失败。

I know there is always a regex option but I gess that cannot be guaranteed 100% because of the recursive nature of JSON and those regex expressions are going to be rather complex.

我知道总是有一个正则表达式选项,但我认为不能保证 100%,因为 JSON 的递归性质,而且这些正则表达式将相当复杂。

Any help will be greatly appreciated!

任何帮助将不胜感激!

回答by Perception

Gson can handle this. Here is an example:

Gson 可以处理这个。下面是一个例子:

public boolean isValid(String json) {
    try {
        new JsonParser().parse(json);
        return true;
    } catch (JsonSyntaxException jse) {
        return false;
    }
}

String json = "{\"color\":\"red\"}{\"var\":\"value\"}";
System.out.println(isValid(json));

Note that Gson does allow some leniency in input JSON, which might not be desired. For example, unquoted keys are automatically converted to quoted ones by the parser. This may or may not be a deal-breaker depending on your expected usage.

请注意,Gson 确实允许对输入 JSON 进行一些宽大处理,这可能是我们不希望看到的。例如,解析器会自动将未加引号的键转换为带引号的键。这可能会或可能不会破坏交易,具体取决于您的预期用途。

回答by rich

Here is our solution for now. Using the two different libraries (gson - first private method and Hymanson - second private method) is not ideal but at least we are passing all of our unit/integration tests. I bet we can do all we need with just the Hymanson tools.

这是我们目前的解决方案。使用两个不同的库(gson - 第一个私有方法和 Hymanson - 第二个私有方法)并不理想,但至少我们通过了所有的单元/集成测试。我敢打赌,我们可以只用 Hymanson 工具做我们需要的一切。

public static boolean isStringValidJSON(String jsonString) {
    return (isJSONStringObjectOrArray(jsonString) && isJSONStringParsable(jsonString));
}

private static boolean isJSONStringObjectOrArray(String jsonString) {
    try {
        JsonElement element = new JsonParser().parse(jsonString);

        return (element.isJsonObject() || element.isJsonArray());
    } catch (JsonSyntaxException jsonEx) {
        return false;
    }
}

private static boolean isJSONStringParsable(String jsonString) {
    try {
        org.codehaus.Hymanson.JsonParser parser = 
          new ObjectMapper().getJsonFactory().createJsonParser(jsonString);
        while(parser.nextToken() != null) {
        }
        return true;
    } catch (JsonParseException e) {
        return false;
    } catch (IOException e) {
        return false;
    }
}

回答by Prashant

Paste your string here. See the output.

将您的字符串粘贴到此处。查看输出。

EDIT:

编辑:

The link above does not work anymore, thisis a good alternative.

上面的链接不再有效,是一个不错的选择。