• 博客园logo
  • 会员
  • 周边
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
PowerCoder
博客园    首页    新随笔    联系   管理    订阅  订阅

使用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类,可以查看下面的官方文档:

LINQ to JSON

下面的官方文档,还演示了如何在JObject类中使用JSONPath:

Querying JSON with SelectToken

 

posted @ 2024-09-07 01:59  PowerCoder  阅读(238)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3