Laravel  
laravel
文档
数据库
架构
入门
php技术
    
Laravelphp
laravel / php / java / vue / mysql / linux / python / javascript / html / css / c++ / c#

c# list转json

作者:′残花败落°   发布日期:2026-04-15   浏览:53

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);
    }
}

解释说明:

  1. 引入命名空间using System;using System.Collections.Generic; 是必要的,前者用于基本的输入输出操作,后者用于使用泛型集合类如 List<T>
  2. 引入Newtonsoft.Json库using Newtonsoft.Json; 引入了第三方库 Newtonsoft.Json,它提供了强大的 JSON 序列化和反序列化功能。如果你还没有安装这个库,可以通过 NuGet 包管理器安装:Install-Package Newtonsoft.Json
  3. 创建List对象List<int> numbers = new List<int> { 1, 2, 3, 4, 5 }; 创建了一个包含整数的列表。
  4. 序列化为JSONstring json = JsonConvert.SerializeObject(numbers); 使用 JsonConvert.SerializeObject 方法将 List<int> 对象转换为 JSON 格式的字符串。
  5. 输出结果Console.WriteLine(json); 将转换后的 JSON 字符串输出到控制台。

这段代码展示了如何将 C# 中的 List<int> 转换为 JSON 字符串。

上一篇:c# 委托和事件

下一篇:c# nmodbus4

大家都在看

c# 二进制

c# 创建目录

c# datatable group by

c# tcp client

c# type.gettype

c# sqlconnection

c# string.format 小数位数

.net和c#

c#获取系统时间

c#游戏开发

Laravel PHP 深圳智简公司。版权所有©2023-2043 LaravelPHP 粤ICP备2021048745号-3

Laravel 中文站