3

I'm using newtonsoft's 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?

0

3 Answers 3

5

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

Sign up to request clarification or add additional context in comments.

1 Comment

Return true for this invalid JSON: {A:{"B": 1}}
3

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

Comments

0

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

2 Comments

Return true for this invalid JSON: {A:{"B": 1}}
Since this is a C# method, I the name should be Pascal case, so IsValidJson.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.