Validate a string to be json or not in asp.net

15,513

Solution 1

Probably the quickest and dirtiest way is to check if the string starts with '{':

public static bool IsJson(string input){ 
    input = input.Trim(); 
    return input.StartsWith("{") && input.EndsWith("}")  
           || input.StartsWith("[") && input.EndsWith("]"); 
} 

Another option is that you could try using the JavascriptSerializer class:

JavaScriptSerializer ser = new JavaScriptSerializer(); 
SomeJSONClass = ser.Deserialize<SomeJSONClass >(json); 

Or you could have a look at JSON.NET:

Solution 2

A working code snippet

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

Source

Share:
15,513
mohsen dorparasti
Author by

mohsen dorparasti

passionate about creating new things I am.

Updated on June 09, 2022

Comments

  • mohsen dorparasti
    mohsen dorparasti almost 2 years

    is there any way to validate a string to be json or not ? other than try/catch .

    I'm using ServiceStack Json Serializer and couldn't find a method related to validation .