C# validate the string value whether it is valid json

时间:2020-10-14 20:41:00   收藏:0   阅读:37
 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         }

 

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!