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

C#构建JSON字符串时无法去除反斜杠问题求助

Fixing Invalid JSON Output and Escape Character Issues in C#

It looks like you're running into two main issues here: invalid JSON structure and unnecessary escape characters (the backslashes) from manual string concatenation. Let's break this down and fix it properly.

Why Your Current Code Causes Problems

  1. Invalid JSON Format: Your code returns multiple objects separated by commas (e.g., {...},{...}) — this isn't valid JSON, since JSON requires a single root object or array. This is likely why the server can't parse it.
  2. Escape Character Confusion: The backslashes you see (like "{\"my_address_type\":\"...\"}") are just how C# displays strings with embedded double quotes in the debugger. However, manual string concatenation is fragile: if your Data values ever contain double quotes, backslashes, or other special characters, it will break the JSON entirely.

The Right Approach: Use JSON Serialization Libraries

Instead of manually building JSON strings (which is error-prone), use a dedicated JSON library like Newtonsoft.Json (Json.NET) (popular for .NET Framework) or System.Text.Json (built into .NET Core/.NET 5+). These libraries handle proper JSON formatting, escape characters, and edge cases automatically.

Example with Newtonsoft.Json

First, install the NuGet package if you haven't:

Install-Package Newtonsoft.Json

Then refactor your method:

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

public string ConstructCylicLoop(string fieldName, int LoopCount, string BadDataLabel, string ImmediateParent)
{
    // Collect all loop items into a list of dictionaries
    var loopItems = new List<Dictionary<string, string>>();

    for (int i = 0; i < LoopCount; i++)
    {
        var loopTestData = new ExcelUtilities().getAPITestData(ApplicationConfiguration.LoopSheetName);
        var currentItem = new Dictionary<string, string>();

        foreach (var loopData in loopTestData)
        {
            // Check if the current entry matches our immediate parent
            if (loopData.TryGetValue("ParentNode", out string parentNode) && parentNode.Equals(ImmediateParent))
            {
                // Extract key and data if they exist
                if (loopData.TryGetValue("Key", out string key) && loopData.TryGetValue("Data", out string data))
                {
                    currentItem[key] = data;
                }
            }
        }

        // Only add the item if it has data
        if (currentItem.Any())
        {
            loopItems.Add(currentItem);
        }
    }

    // Serialize the list to a valid JSON array
    // If you need a single object instead of an array when LoopCount = 1, add a check here
    return JsonConvert.SerializeObject(loopItems);
}

Example with System.Text.Json (Built-in)

If you're using .NET Core/.NET 5+, you can use the built-in library without installing extra packages:

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

public string ConstructCylicLoop(string fieldName, int LoopCount, string BadDataLabel, string ImmediateParent)
{
    var loopItems = new List<Dictionary<string, string>>();

    for (int i = 0; i < LoopCount; i++)
    {
        var loopTestData = new ExcelUtilities().getAPITestData(ApplicationConfiguration.LoopSheetName);
        var currentItem = new Dictionary<string, string>();

        foreach (var loopData in loopTestData)
        {
            if (loopData.TryGetValue("ParentNode", out string parentNode) && parentNode.Equals(ImmediateParent))
            {
                if (loopData.TryGetValue("Key", out string key) && loopData.TryGetValue("Data", out string data))
                {
                    currentItem[key] = data;
                }
            }
        }

        if (currentItem.Any())
        {
            loopItems.Add(currentItem);
        }
    }

    // Serialize to JSON array
    return JsonSerializer.Serialize(loopItems);
}

What This Fixes

  • Valid JSON Structure: The output will be a proper JSON array (e.g., [{"my_address_type":"primarypropertyaddress",...}, {...}]) which servers can parse correctly.
  • No Unnecessary Escapes: The serialization library will handle double quotes and special characters correctly — no more unwanted backslashes in the actual JSON sent to the server.
  • Maintainability: This approach is easier to debug and modify than manual string concatenation, especially if your JSON structure gets more complex.

Optional: Single Object Instead of Array

If you need to return a single object (not an array) when LoopCount = 1, add a quick check before serialization:

if (loopItems.Count == 1)
{
    return JsonConvert.SerializeObject(loopItems[0]); // or JsonSerializer.Serialize for System.Text.Json
}
else
{
    return JsonConvert.SerializeObject(loopItems);
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 07:17:08