使用Newtonsoft直接读取Json格式文本(Linq to Json)

171 阅读2分钟

使用Newtonsoft直接读取Json格式文本(Linq to Json)

使用 Newtonsoft.Json(通常简称为 Newtonsoft)可以轻松地处理 JSON 格式的文本。Newtonsoft.Json 是 .NET 中一个流行的 JSON 处理库,它提供了丰富的功能和灵活性。

以下是使用 Newtonsoft.Json 进行 Linq to JSON 的示例代码:

首先,你需要在项目中安装 Newtonsoft.Json 包。你可以通过 NuGet 包管理器或者 .NET CLI 来安装该包。如果你使用 Visual Studio,可以右键点击项目,选择“管理 NuGet 程序包”,然后搜索并安装 Newtonsoft.Json。

接下来,假设有一个 JSON 格式的文本如下:

 {
   "name": "John Doe",
   "age": 30,
   "email": "john.doe@example.com",
   "address": {
     "city": "New York",
     "zipCode": "10001"
   },
   "hobbies": [
     "reading",
     "swimming",
     "cooking"
   ]
 }

使用 Newtonsoft.Json,你可以读取并解析这个 JSON 文本:

 using System;
 using Newtonsoft.Json.Linq;
 ​
 namespace JsonParsing
 {
     class Program
     {
         static void Main()
         {
             // JSON 格式的文本
             string jsonText = @"{
                 'name': 'John Doe',
                 'age': 30,
                 'email': 'john.doe@example.com',
                 'address': {
                     'city': 'New York',
                     'zipCode': '10001'
                 },
                 'hobbies': [
                     'reading',
                     'swimming',
                     'cooking'
                 ]
             }";
 ​
             // 解析 JSON 文本为 JObject
             JObject jsonObject = JObject.Parse(jsonText);
 ​
             // 获取具体属性值
             string name = (string)jsonObject["name"];
             int age = (int)jsonObject["age"];
             string email = (string)jsonObject["email"];
 ​
             JObject address = (JObject)jsonObject["address"];
             string city = (string)address["city"];
             string zipCode = (string)address["zipCode"];
 ​
             JArray hobbies = (JArray)jsonObject["hobbies"];
 ​
             Console.WriteLine("Name: " + name);
             Console.WriteLine("Age: " + age);
             Console.WriteLine("Email: " + email);
             Console.WriteLine("City: " + city);
             Console.WriteLine("Zip Code: " + zipCode);
 ​
             Console.WriteLine("Hobbies:");
             foreach (var hobby in hobbies)
             {
                 Console.WriteLine("- " + (string)hobby);
             }
         }
     }
 }

运行以上代码,你将得到输出:

 Name: John Doe
 Age: 30
 Email: john.doe@example.com
 City: New York
 Zip Code: 10001
 Hobbies:
 - reading
 - swimming
 - cooking

在这个示例中,我们使用 JObject.Parse 方法将 JSON 文本解析为 JObject,然后通过键值索引的方式获取其中的属性值。如果属性是对象或数组类型,我们可以继续使用 JObjectJArray 对象进行进一步的操作。

通过使用 Newtonsoft.Json,你可以灵活地读取和解析 JSON 格式的文本,并方便地提取所需的数据。它是 .NET 开发中处理 JSON 数据的强大工具。