c#winform构建json串数据
时间: 2024-10-25 10:13:18 浏览: 8
C# WinForm 解析json並寫入DataGridView
在C# WinForm中,构建JSON字符串通常会使用.NET框架提供的`System.Text.Json`库或者第三方库如`Newtonsoft.Json`。以下是使用`System.Text.Json`创建JSON字符串的基本步骤:
1. 引入所需命名空间:
```csharp
using System.Text.Json;
```
2. 定义一个需要转换成JSON的对象或集合,例如:
```csharp
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
List<Person> people = new List<Person>
{
new Person { Name = "张三", Age = 30 },
new Person { Name = "李四", Age = 35 }
};
```
3. 使用`JsonSerializer.Serialize()`方法将对象序列化为JSON字符串:
```csharp
string jsonString = JsonSerializer.Serialize(people);
```
完整示例:
```csharp
using System;
using System.Text.Json;
namespace ConsoleApp
{
class Program
{
static void Main(string[] args)
{
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
List<Person> people = new List<Person>
{
new Person { Name = "张三", Age = 30 },
new Person { Name = "李四", Age = 35 }
};
string jsonString = JsonSerializer.Serialize(people);
Console.WriteLine(jsonString); // 输出:[{"Name":"张三","Age":30},{"Name":"李四","Age":35}]
//
阅读全文