C# 的 List 集合表示所有部门,然后将其转换为 JSON 数据返回给前端 详细步骤
时间: 2024-03-05 09:50:59 浏览: 172
实体类的简单基础应用 List 与 JSON 互相转换
以下是将 C# 的 List 集合转换为 JSON 数据并返回给前端的详细步骤:
1. 创建一个 C# 类型来表示部门信息
```csharp
public class Department
{
public int Id { get; set; }
public string Name { get; set; }
public string Code { get; set; }
public int? ParentId { get; set; }
public string Manager { get; set; }
}
```
2. 创建一个 List 对象来存储所有部门信息
```csharp
List<Department> departments = new List<Department>();
```
3. 将部门信息添加到 List 对象中
```csharp
departments.Add(new Department { Id = 1, Name = "总经理办公室", Code = "GM", ParentId = null, Manager = "李总" });
departments.Add(new Department { Id = 2, Name = "人事部", Code = "HR", ParentId = 1, Manager = "张经理" });
departments.Add(new Department { Id = 3, Name = "财务部", Code = "Finance", ParentId = 1, Manager = "王经理" });
departments.Add(new Department { Id = 4, Name = "市场部", Code = "Marketing", ParentId = 1, Manager = "赵经理" });
departments.Add(new Department { Id = 5, Name = "销售部", Code = "Sales", ParentId = 4, Manager = "刘经理" });
```
4. 将 List 对象序列化为 JSON 数据
```csharp
using System.Web.Script.Serialization;
JavaScriptSerializer serializer = new JavaScriptSerializer();
string json = serializer.Serialize(departments);
```
5. 将 JSON 数据返回给前端
```csharp
return Content(json, "application/json");
```
以上代码仅供参考,实际实现时可能需要根据具体情况进行修改。注意,在序列化时需要引入 System.Web.Script.Serialization 命名空间。
阅读全文