开发者

Need a string JSON Validator [duplicate]

This question already has answers here: How to make sure that string is valid JSON using JSON.NET (13 answers) Closed 6 years ago.

I'm using newtonsoft's开发者_Go百科 JSON.Net and loving every minute of it.

However, I am using JObject.Parse(jsonString) to grab a JToken from a response string. If I send invalid JSON, I get an exception. I can catch the exception, but I would like to, be able to test the string first before sending it to Parse.

Maybe something akin to JObject.TryParse() (which doesn't exist).

I'd even take bool ValidJson(string)

I know there's JSONLint out there, but I would really like to keep the external calls to a minimum.

Any ideas?


The simplest solution would be to write a function which calls JObject.Parse and returns false if it throws a Newtonsoft.Json.JsonReaderException.


Use JContainer.Parse(str) method to check if the str is a valid Json. If this throws exception then it is not a valid Json.

JObject.Parse - Can be used to check if the string is a valid Json object
JArray.Parse - Can be used to check if the string is a valid Json Array
JContainer.Parse - Can be used to check for both Json object & Array


A working code snippet

public bool isValidJSON(string json)
{
    try
    {
        JToken token = JObject.Parse(json);
        return true;
    }
    catch(Exception ex)
    {
        return false;
    }
}

Thanks to MRAB

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜