使用Json.NET验证json字符串是否格式正确
Json.NET中的JObject类非常强大,我们可以用它来验证一个json字符串是否格式正确:
using Newtonsoft.Json.Linq; namespace NetCoreJsonObject { internal class Program { static void Main(string[] args) { string json = "{\"name\":\"Jack\",\"age\":30}";//格式正确的json字符串 JObject o = JObject.Parse(json); Console.WriteLine(o.ToString()); json = "{\"name\":\"Jack\",\"age:30}";//格式错误的json字符串 try { o = JObject.Parse(json);//格式错误的json字符串,会在JObject.Parse方法中抛出Newtonsoft.Json.JsonReaderException } catch (Exception ex) { Console.WriteLine(ex.ToString()); } Console.WriteLine("Press any key to end..."); Console.ReadLine(); } } }
关于Json.NET的JObject类,可以查看下面的官方文档:
下面的官方文档,还演示了如何在JObject类中使用JSONPath:
Querying JSON with SelectToken