You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在C#中如何将List<string>转换为指定结构的JSON

问题

我有一个包含以下项的List<string>:

  • 001-HA-Manager
  • 001-HA-Supervisor
  • 001-HA-Validation
  • 001-HA-DocumentReviewer
  • 001-HA-ManagerReviewer
  • 002-HA-Manager
  • 002-HA-Supervisor
  • 002-HA-Validation

需要将这些项转换为如下JSON格式:

{
  "Project": [
    {
      "ProjectCode": "001",
      "Groups": ["Manager", "Supervisor", "Validation", "DocumentReviewer", "ManagerReviewer"]
    },
    {
      "ProjectCode": "002",
      "Groups": ["Manager", "Supervisor", "Validation"]
    }
  ]
}
解决方案

可以通过分组和字符串分割实现转换,以下是C#示例代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;

class Program
{
    static void Main()
    {
        List<string> items = new List<string>
        {
            "001-HA-Manager",
            "001-HA-Supervisor",
            "001-HA-Validation",
            "001-HA-DocumentReviewer",
            "001-HA-ManagerReviewer",
            "002-HA-Manager",
            "002-HA-Supervisor",
            "002-HA-Validation"
        };

        // 按项目代码分组
        var grouped = items.GroupBy(item => item.Split('-')[0])
                           .Select(g => new 
                           {
                               ProjectCode = g.Key,
                               Groups = g.Select(item => item.Split('-')[2]).ToList()
                           });

        // 构造JSON结构
        var result = new { Project = grouped };

        // 序列化为格式化后的JSON
        string json = JsonSerializer.Serialize(result, new JsonSerializerOptions { WriteIndented = true });
        Console.WriteLine(json);
    }
}

代码说明

  1. 分组处理:用GroupBy按字符串分割后的第一部分(项目代码)分组
  2. 提取分组名称:对每个分组内的项,取分割后的第三部分作为分组名并整理成列表
  3. JSON序列化:使用System.Text.Json将对象转为带缩进的JSON字符串,匹配要求格式

内容的提问来源于stack exchange,提问作者Macdroopy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 17:17:48