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
I'm using the following code to write the json file
string location = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string userDataPreset = @"{UserData: [{Language: ""NL"", location: " location "}]}";
File.WriteAllText(userData, userDataPreset);
This creates the following 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?
CodePudding user response:
to fix the string you can use an Escape method
location=Regex.Escape(location);
but the most relable method is to create an anonymous object and serialize it
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
{
"UserData": [
{
"Language": "NL",
"Location": "C:\\Users\\stage\\OneDrive\\Documenten"
}
]
}