7

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 .

mohsen dorparasti
  • 8,107
  • 7
  • 41
  • 61
  • possible duplicate of [Check JSON and XML is valid? c#](http://stackoverflow.com/questions/8766974/check-json-and-xml-is-valid-c-sharp) – Dennis Traub Aug 06 '12 at 20:42
  • that solution uses try/catch . I'm looking for method like TryParse that we have for int,date,... . just to check if string contains a valid json structure or not – mohsen dorparasti Aug 06 '12 at 20:48
  • Possible duplicate of [How to make sure that string is Valid JSON using JSON.NET](http://stackoverflow.com/questions/14977848/how-to-make-sure-that-string-is-valid-json-using-json-net) – Michael Freidgeim Aug 05 '16 at 06:55

3 Answers3

16

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:

skub
  • 2,266
  • 23
  • 33
1

A working code snippet

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

Source

Community
  • 1
  • 1
Durai Amuthan.H
  • 31,670
  • 10
  • 160
  • 241
0

You can find a couple of regular expressions to validate JSON over here: Regex to validate JSON

It's written in PHP but should be adaptable to C#.

Community
  • 1
  • 1
Dennis Traub
  • 50,557
  • 7
  • 93
  • 108