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

C#读取含未转义双引号的JSON文件反序列化报错求助

解决JSON未转义双引号导致的反序列化异常

问题核心:网站生成的JSON原本带有正确的转义序列(比如\"information\"),但保存到本地后转义丢失,变成了未转义的双引号,导致JSON格式非法,Newtonsoft.Json解析时抛出异常。同时原JSON中还存在多余的逗号(比如键值对末尾、对象末尾的逗号),也会影响解析。

方案1:手动修复本地JSON文件

这是最直接可靠的方式,修正两个问题:

  1. 给字符串内的未转义双引号添加反斜杠\,比如把"information"改成\"information",单个双引号"改成\"
  2. 删除JSON中多余的逗号(比如"showViewLogs": true,和},后面的逗号)

修正后的合法JSON示例:

{
  "configuration": {
    "aboutDisplayServerName": false,
    "aboutText": "This application/solution allows public safety personnel to relay important emergency  \"information\" to your computer. Currently we are testing and  along with along with one double quote \" and two single quotes ''. Let's see.",
    "applicationName": "My Desktop",
    "loggingLevel": "INFO",
    "logonScreenAlertsEnabled": true,
    "maxAlertsInHistory": 5,
    "minSecondsBeforeClosingAlert": 1,
    "name": "Gary",
    "panicButtonCooldownMillis": 0,
    "TimeOutMillis": 10000,
    "requestTimeoutMillis": 30000,
    "showExit": true,
    "showInSystemTrayMode": "Always",
    "showRecentMessages": true,
    "showViewLogs": true
  }
}

方案2:在C#代码中自动修复非法JSON

如果无法手动修改文件,可以在读取JSON后先做格式修复,再反序列化:

public static void LoadJson()
{
    Configuration configuration = new Configuration();
    string mConfigFileLoc = @"C:\ProgramData\My Desktop\Configuration.json";
    
    using (StreamReader r = new StreamReader(mConfigFileLoc))
    {
        string json = r.ReadToEnd();
        
        // 修复字符串内的未转义双引号
        bool inString = false;
        StringBuilder fixedJson = new StringBuilder();
        for (int i = 0; i < json.Length; i++)
        {
            char c = json[i];
            if (c == '"')
            {
                if (!inString)
                {
                    inString = true;
                    fixedJson.Append(c);
                }
                else
                {
                    // 跳过已经转义的双引号
                    if (i > 0 && json[i-1] == '\\')
                    {
                        fixedJson.Append(c);
                    }
                    else
                    {
                        // 给未转义的双引号加反斜杠
                        fixedJson.Append('\\').Append(c);
                    }
                }
            }
            else if (c == '\\' && inString && i+1 < json.Length && json[i+1] == '"')
            {
                // 保留合法的转义双引号
                fixedJson.Append(c).Append(json[i+1]);
                i++;
            }
            else
            {
                fixedJson.Append(c);
            }
        }
        
        // 删除多余的逗号(比如对象/数组末尾的逗号)
        string cleanedJson = System.Text.RegularExpressions.Regex.Replace(fixedJson.ToString(), @",\s*([}\]])", "$1");
        
        // 执行反序列化
        var objConfiguration = JsonConvert.DeserializeObject(cleanedJson);
        JObject jObject = ((JObject)objConfiguration);
        configuration = jObject.ToObject<Configuration>();
    }
}

注意:自动修复逻辑有局限性,如果JSON中存在复杂的特殊字符场景,可能需要调整代码逻辑,优先推荐手动修复文件。

方案3:从源头避免转义丢失

下载JSON时用正确的方式保存,防止转义字符被自动去除:

  • 不要用记事本直接复制网页中的JSON内容保存(记事本可能会处理转义字符)
  • 在C#中下载时,直接将响应流写入文件,跳过字符串转换步骤:
using (var client = new HttpClient())
{
    using (var stream = await client.GetStreamAsync("目标JSON接口的URL"))
    {
        using (var fileStream = new FileStream(mConfigFileLoc, FileMode.Create))
        {
            await stream.CopyToAsync(fileStream);
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.04 13:45:24