c#如何解析json集合[ {"categories":"衬衫","data":10}, {"categories":"格子衫","data":20} ]
时间: 2024-02-09 20:05:52 浏览: 31
在C#中解析JSON集合可以使用Json.NET库(也称为Newtonsoft.Json)。以下是使用Json.NET解析JSON集合的示例代码:
```csharp
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
public class Item
{
public string categories { get; set; }
public int data { get; set; }
}
public class Program
{
public static void Main()
{
string json = @"[
{ ""categories"": ""衬衫"", ""data"": 10 },
{ ""categories"": ""格子衫"", ""data"": 20 }
]";
List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);
foreach (Item item in items)
{
Console.WriteLine("Categories: " + item.categories);
Console.WriteLine("Data: " + item.data);
Console.WriteLine();
}
}
}
```
在上面的示例中,我们定义了一个`Item`类来表示JSON中的每个对象。然后,我们使用`JsonConvert.DeserializeObject`方法将JSON字符串转换为`List<Item>`对象。最后,我们可以遍历`items`列表并访问每个对象的属性。
请注意,为了使用Json.NET库,您需要在项目中安装Json.NET NuGet包。
相关推荐
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)