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

如何在JSON文件中正确格式化C#目录路径?

JSON中文件夹路径格式错误的解决方法

问题背景

你手动拼接JSON字符串保存文件夹路径时,生成的JSON不符合标准格式:路径未被双引号包裹,反斜杠也未转义。相关代码及输出如下:

原C#代码

string location = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string userDataPreset = @"{UserData: [{Language: ""NL"", location: " + location + "}]}";
File.WriteAllText(userData, userDataPreset);

错误的JSON输出

{
  "UserData": [
    {
      "Language": "NL",
      "location": C:\Users\stage\OneDrive\Documenten
    }
  ]
}

期望的标准JSON格式

{
  "UserData": [
    {
      "Language": "NL",
      "location": "C:\\Users\\stage\\OneDrive\\Documenten"
    }
  ]
}

问题根源

手动拼接JSON时,你遗漏了两个关键要求:

  1. JSON规定字符串类型必须用双引号包裹,你没给路径加引号;
  2. JSON里反斜杠是特殊字符,必须转义为\\,你直接使用了原始路径中的单反斜杠。

另外,手动拼接JSON极易出现引号不匹配、特殊字符遗漏等问题,代码维护性极差。

推荐解决方案:使用JSON序列化库

不要手动拼接JSON,改用官方或成熟的序列化库,它们会自动处理字符串的引号和转义逻辑。

方案1:使用System.Text.Json(.NET内置)

适用于.NET Core 3.0+、.NET 5+版本,无需额外安装包:

using System.Text.Json;
using System.IO;

// 获取文档路径
string location = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

// 定义数据结构(强类型更安全)
var userData = new
{
    UserData = new[]
    {
        new { Language = "NL", location = location }
    }
};

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

// 写入文件
File.WriteAllText("userData.json", jsonContent);

方案2:使用Newtonsoft.Json(Json.NET)

如果项目使用.NET Framework或需要更灵活的序列化配置,可通过NuGet安装Newtonsoft.Json包:

using Newtonsoft.Json;
using System.IO;

string location = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

var userData = new
{
    UserData = new[]
    {
        new { Language = "NL", location = location }
    }
};

// 序列化为格式化后的JSON
string jsonContent = JsonConvert.SerializeObject(userData, Formatting.Indented);

// 写入文件
File.WriteAllText("userData.json", jsonContent);

临时方案:手动修正字符串拼接(不推荐)

如果必须手动拼接,需要手动处理引号和转义:

string location = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
// 转义反斜杠并添加双引号
string escapedLocation = $"\"{location.Replace("\\", "\\\\")}\"";
// 拼接标准JSON格式的字符串
string userDataPreset = $"{{\"UserData\": [{{\"Language\": \"NL\", \"location\": {escapedLocation}}}]}}";
File.WriteAllText("userData.json", userDataPreset);

⚠️ 注意:这种方式仅适用于简单场景,复杂数据结构下极易出错,不建议长期使用。

内容的提问来源于stack exchange,提问作者Marco N.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 22:25:18