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

如何手动将指定JSON格式字符串转换为List<TestClass>集合?

手动解析JSON字符串到List的实现方案

核心思路

由于直接按逗号分割会被对象内部的逗号干扰,我们可以通过括号计数+引号状态判断来精准识别独立的JSON对象:

  • 遍历字符串时,维护括号计数(遇到{加1,遇到}减1)
  • 同时跟踪是否处于字符串引号内(引号内的{}、逗号不参与计数和分割判断)
  • 当括号计数回到0且当前字符是逗号时,即可分割出一个完整的对象片段

完整代码实现

1. 分割多个JSON对象

先将处理后的字符串拆分为单个对象的JSON片段:

private static List<string> SplitObjects(string input)
{
    var result = new List<string>();
    int braceCount = 0;
    bool inQuotes = false;
    int startIndex = 0;

    for (int i = 0; i < input.Length; i++)
    {
        char c = input[i];
        if (c == '"')
        {
            inQuotes = !inQuotes;
        }
        else if (!inQuotes)
        {
            if (c == '{')
            {
                braceCount++;
            }
            else if (c == '}')
            {
                braceCount--;
                if (braceCount == 0)
                {
                    result.Add(input.Substring(startIndex, i - startIndex + 1).Trim());
                    // 跳过对象间的逗号
                    if (i + 1 < input.Length && input[i + 1] == ',')
                    {
                        startIndex = i + 2;
                        i++;
                    }
                    else
                    {
                        startIndex = i + 1;
                    }
                }
            }
        }
    }

    // 处理最后一个无逗号结尾的对象
    if (startIndex < input.Length && braceCount == 0)
    {
        result.Add(input.Substring(startIndex).Trim());
    }

    return result;
}

2. 解析单个对象到TestClass

将单个JSON对象片段转换为TestClass实例:

private static TestClass ParseTestClass(string jsonObject)
{
    var testObj = new TestClass();
    var content = jsonObject.Trim().TrimStart('{').TrimEnd('}');
    int braceCount = 0;
    bool inQuotes = false;
    int startIndex = 0;

    for (int i = 0; i < content.Length; i++)
    {
        char c = content[i];
        if (c == '"')
        {
            inQuotes = !inQuotes;
        }
        else if (!inQuotes)
        {
            if (c == '{') braceCount++;
            else if (c == '}') braceCount--;
            else if (c == ',' && braceCount == 0)
            {
                ProcessKeyValuePair(content.Substring(startIndex, i - startIndex).Trim(), testObj);
                startIndex = i + 1;
            }
        }
    }

    // 处理最后一组键值对
    if (startIndex < content.Length)
    {
        ProcessKeyValuePair(content.Substring(startIndex).Trim(), testObj);
    }

    return testObj;
}

3. 处理键值对映射

将JSON键值对赋值到TestClass的属性:

private static void ProcessKeyValuePair(string kvPair, TestClass testObj)
{
    bool inQuotes = false;
    int colonIndex = -1;
    // 找到第一个不在引号内的冒号,分割键和值
    for (int i = 0; i < kvPair.Length; i++)
    {
        char c = kvPair[i];
        if (c == '"')
        {
            inQuotes = !inQuotes;
        }
        else if (!inQuotes && c == ':')
        {
            colonIndex = i;
            break;
        }
    }

    if (colonIndex == -1) return;

    var key = kvPair.Substring(0, colonIndex).Trim().Trim('"');
    var value = kvPair.Substring(colonIndex + 1).Trim();

    switch (key.ToLower())
    {
        case "ours":
            int.TryParse(value, out int ours);
            testObj.Ours = ours;
            break;
        case "theirs":
            testObj.Theirs = value.Trim('"');
            break;
        case "companyid":
            int.TryParse(value, out int companyId);
            testObj.CompanyId = companyId;
            break;
    }
}

4. 调用示例

// 假设已移除外层{"data":[和]}的目标字符串
string processedInput = "{\"ours\":176,\"theirs\":\"TAMPA\",\"companyId\":111},{\"ours\":176,\"theirs\":\"ORLANDO\",\"companyId\":111}";

List<string> objectStrings = SplitObjects(processedInput);
List<TestClass> allValues = new List<TestClass>();

foreach (var objStr in objectStrings)
{
    allValues.Add(ParseTestClass(objStr));
}

// 输出验证
foreach (var item in allValues)
{
    Console.WriteLine($"Ours: {item.Ours}, Theirs: {item.Theirs}, CompanyId: {item.CompanyId}");
}

关键细节说明

  • 支持引号内的特殊字符(比如字符串值中的逗号、括号),避免错误分割
  • 键名做了大小写不敏感处理,适配JSON小写键与TestClass PascalCase属性的映射
  • 包含基础错误处理(如整数解析失败时保持默认值)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 08:57:17