1private static bool IsValidJson(string strInput)
2{
3 if (string.IsNullOrWhiteSpace(strInput)) { return false;}
4 strInput = strInput.Trim();
5 if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
6 (strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
7 {
8 try
9 {
10 var obj = JToken.Parse(strInput);
11 return true;
12 }
13 catch (JsonReaderException jex)
14 {
15 //Exception in parsing json
16 Console.WriteLine(jex.Message);
17 return false;
18 }
19 catch (Exception ex) //some other exception
20 {
21 Console.WriteLine(ex.ToString());
22 return false;
23 }
24 }
25 else
26 {
27 return false;
28 }
29}
1private static bool IsValidJson(string strInput)
2{//Using JSON.Net
3 if (string.IsNullOrWhiteSpace(strInput)) { return false;}
4 strInput = strInput.Trim();
5 if ((strInput.StartsWith("{") && strInput.EndsWith("}")) || //For object
6 (strInput.StartsWith("[") && strInput.EndsWith("]"))) //For array
7 {
8 try
9 {
10 var obj = JToken.Parse(strInput);
11 return true;
12 }
13 catch (JsonReaderException jex)
14 {
15 //Exception in parsing json
16 Console.WriteLine(jex.Message);
17 return false;
18 }
19 catch (Exception ex) //some other exception
20 {
21 Console.WriteLine(ex.ToString());
22 return false;
23 }
24 }
25 else
26 {
27 return false;
28 }
29}
30
31//or Without JSON.Net
32//You can utilize .Net framework 4.5 System.Json namespace ,like:
33
34string jsonString = "someString";
35try
36{
37 var tmpObj = JsonValue.Parse(jsonString);
38}
39catch (FormatException fex)
40{
41 //Invalid json format
42 Console.WriteLine(fex);
43}
44catch (Exception ex) //some other exception
45{
46 Console.WriteLine(ex.ToString());
47}//(But, you have to install System.Json through Nuget package manager using
48//command: PM> Install-Package System.Json -Version 4.0.20126.16343 on Package Manager Console)