Confirm json string or not in asp.net

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.

+6
json servicestack
Aug 6 2018-12-12T00:
source share
3 answers

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:

+14
Aug 07 2018-12-12T00:
source share
— -

Working code snippet

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

Source

+1
Jun 19 '15 at 7:28
source share

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 #.

0
Aug 6 2018-12-12T00:
source share



All Articles