简体   繁体   English

C# json 格式的目录路径

[英]C# Directory path to json formatting

I'm trying to save a folder path in a json file but I can't seem to find/figure out how to get it to parse it correctly我正在尝试将文件夹路径保存在 json 文件中,但我似乎无法找到/弄清楚如何让它正确解析它

I'm using the following code to write the json file我正在使用以下代码编写 json 文件

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

This creates the following json:这将创建以下 json:

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

But I need it to become the following, with the double // and "":但我需要它变成下面这样,带有双 // 和“”:

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

What am I missing to parse this path correctly?我缺少什么来正确解析这条路径?

to fix the string you can use an Escape method要修复字符串,您可以使用 Escape 方法

location=Regex.Escape(location);

but the most relable method is to create an anonymous object and serialize it但最可靠的方法是创建一个匿名 object 并将其序列化

    var data = new { UserData = new[] { new { Language = "NL", Location = location } } };
    var json = System.Text.Json.JsonSerializer.Serialize(data, new JsonSerializerOptions { WriteIndented = true});
    File.WriteAllText(userData, json);

json json

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM