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 .
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 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:
- http://james.newtonking.com/projects/json-net.aspx
- http://james.newtonking.com/projects/json/help/index.html?topic=html/SerializingJSON.htm
Method 2
A working code snippet
public bool isValidJSON(String json)
{
try
{
JToken token = JObject.Parse(json);
return true;
}
catch (Exception ex)
{
return false;
}
}
Method 3
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#.
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0