Is there a way to check the string as json or not? except try / catch.
I am using ServiceStack Json Serializer and cannot find the method related to validation.
Probably the fastest and dirtiest way is to check if the line starts with '{' :
public static bool IsJson(string input){ input = input.Trim(); return input.StartsWith("{") && input.EndsWith("}") || input.StartsWith("[") && input.EndsWith("]"); }
Another option is to try using the JavascriptSerializer class:
JavaScriptSerializer ser = new JavaScriptSerializer(); SomeJSONClass = ser.Deserialize<SomeJSONClass >(json);
Or you could take a look at JSON.NET:
Working code snippet
public bool isValidJSON(String json) { try { JToken token = JObject.Parse(json); return true; } catch (Exception ex) { return false; } }
Source
You can find a couple of regular expressions for checking JSON here: Regex for checking JSON
It is written in PHP, but must be adapted to C #.