Coder Perfect

Using JSON.NET, how can I verify that a string is acceptable JSON?

Problem

I’m working with a raw string. I’m only looking to see if the string is JSON-compliant. JSON.NET is what I’m utilizing.

Asked by Imran Qadir Baksh – Baloch

Solution #1

Through Code:

Your best bet is to use parse inside a try-catch block, with a catch exception thrown if parsing fails. (There isn’t a TryParse method that I’m aware of.)

(Using JSON.Net)

The simplest method is to use JToken to parse the string. Parse, as well as check whether the string begins with or [and finishes with or] (added from this answer):

private static bool IsValidJson(string strInput)
{
    if (string.IsNullOrWhiteSpace(strInput)) { return false;}
    strInput = strInput.Trim();
    if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
        (strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
    {
        try
        {
            var obj = JToken.Parse(strInput);
            return true;
        }
        catch (JsonReaderException jex)
        {
            //Exception in parsing json
            Console.WriteLine(jex.Message);
            return false;
        }
        catch (Exception ex) //some other exception
        {
            Console.WriteLine(ex.ToString());
            return false;
        }
    }
    else
    {
        return false;
    }
}

The decision to include checks for or [etc.] was motivated by the fact that JToken. Values like “1234” or “‘a string'” would be considered valid tokens by Parse. Another possibility is to use both JObjects. JArray and Parse Check to see if any of them succeeds in parsing, although I believe checking for and [] should be easier. (Thanks to @RhinoDevel for bringing it to my attention.)

Without JSON.Net

You can make use of. System based on the.NET Framework 4.5. Namespaces in Json, such as:

string jsonString = "someString";
try
{
    var tmpObj = JsonValue.Parse(jsonString);
}
catch (FormatException fex)
{
    //Invalid json format
    Console.WriteLine(fex);
}
catch (Exception ex) //some other exception
{
    Console.WriteLine(ex.ToString());
}

(However, you must use the Nuget package manager to install System.Json with the command: PM> Install-Package System.Json -Version 4.0.20126.16343 on the Package Manager Console.) (Stolen from this site)

Non-Code way:

I like to use existing on-line tools when there is a tiny json string and I am trying to detect a mistake in the json string. I normally perform the following:

Answered by Habib

Solution #2

Make use of JContainer. To see if the str is a valid Json, use the Parse(str) method. This is not a legitimate Json if it throws an exception.

JObject. Parse – Determines whether a string is a valid Json object JArray. Parse – This method can be used to determine if a string is a valid Json Array. JContainer. Parse – This function can be used to check for both Json objects and arrays.

Answered by Senthilkumar Viswanathan

Solution #3

You might develop an extension method based on Habib’s response:

public static bool ValidateJSON(this string s)
{
    try
    {
        JToken.Parse(s);
        return true;
    }
    catch (JsonReaderException ex)
    {
        Trace.WriteLine(ex);
        return false;
    }
}

The following is an example of how it could be used:

if(stringObject.ValidateJSON())
{
    // Valid JSON!
}

Answered by Tom Beech

Solution #4

To add to @Habib’s response, you can also check if the given JSON is of a valid type:

public static bool IsValidJson<T>(this string strInput)
{
    if(string.IsNullOrWhiteSpace(strInput)) return false;

    strInput = strInput.Trim();
    if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
        (strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
    {
        try
        {
            var obj = JsonConvert.DeserializeObject<T>(strInput);
            return true;
        }
        catch // not valid
        {             
            return false;
        }
    }
    else
    {
        return false;
    }
}

Answered by Jalal

Solution #5

JToken was discovered. Parse parses invalid JSON wrongly, such as the following:

{
"Id" : , 
"Status" : 2
}

The JSON string is invalid when pasted into http://jsonlint.com/.

So I use:

public static bool IsValidJson(this string input)
{
    input = input.Trim();
    if ((input.StartsWith("{") && input.EndsWith("}")) || //For object
        (input.StartsWith("[") && input.EndsWith("]"))) //For array
    {
        try
        {
            //parse the input into a JObject
            var jObject = JObject.Parse(input);

            foreach(var jo in jObject)
            {
                string name = jo.Key;
                JToken value = jo.Value;

                //if the element has a missing value, it will be Undefined - this is invalid
                if (value.Type == JTokenType.Undefined)
                {
                    return false;
                }
            }
        }
        catch (JsonReaderException jex)
        {
            //Exception in parsing json
            Console.WriteLine(jex.Message);
            return false;
        }
        catch (Exception ex) //some other exception
        {
            Console.WriteLine(ex.ToString());
            return false;
        }
    }
    else
    {
        return false;
    }

    return true;
}

Answered by Andrew Roberts

Post is based on https://stackoverflow.com/questions/14977848/how-to-make-sure-that-string-is-valid-json-using-json-net