C# validate the string value whether it is valid json

 1 using Newtonsoft.Json;
 2 using Newtonsoft.Json.Linq;
 3 
 4  static void Main(string[] args)
 5         {
 6             TestJsonValid();
 7             Console.ReadLine();
 8         }
 9 
10         static void TestJsonValid()
11         {
12             var obj = new
13             {
14                 Id = 1,
15                 Name = "Fred",
16                 Age = 33
17             };
18             string jsonValue = JsonConvert.SerializeObject(obj, Formatting.Indented);
19             bool result = ValidJson(jsonValue);
20             Console.WriteLine(result);
21         }
22 
23         static bool ValidJson(string msgValue)
24         {
25             try
26             {
27                 JToken token = JObject.Parse(msgValue);
28                 return true;
29             }
30             catch(Exception ex)
31             {
32                 return false;
33             }
34         }

 

posted @ 2020-10-14 14:54  FredGrit  阅读(148)  评论(0编辑  收藏  举报