using System;
using System.Collections.Generic;
using Newtonsoft.Json;
class Program
{
static void Main()
{
// 创建一个包含一些整数的List
List<int> numbers = new List<int> { 1, 2, 3, 4, 5 };
// 使用JsonConvert.SerializeObject方法将List转换为JSON字符串
string json = JsonConvert.SerializeObject(numbers);
// 输出转换后的JSON字符串
Console.WriteLine(json);
}
}
using System; 和 using System.Collections.Generic; 是必要的,前者用于基本的输入输出操作,后者用于使用泛型集合类如 List<T>。using Newtonsoft.Json; 引入了第三方库 Newtonsoft.Json,它提供了强大的 JSON 序列化和反序列化功能。如果你还没有安装这个库,可以通过 NuGet 包管理器安装:Install-Package Newtonsoft.Json。List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; 创建了一个包含整数的列表。string json = JsonConvert.SerializeObject(numbers); 使用 JsonConvert.SerializeObject 方法将 List<int> 对象转换为 JSON 格式的字符串。Console.WriteLine(json); 将转换后的 JSON 字符串输出到控制台。这段代码展示了如何将 C# 中的 List<int> 转换为 JSON 字符串。
上一篇:c# 委托和事件
下一篇:c# nmodbus4
Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3
Laravel 中文站