0

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?

Charlieface
  • 52,284
  • 6
  • 19
  • 43
Marco N.
  • 73
  • 1
  • 7
  • 6
    Don't construct json string manually. Create a class, then serialize it. Then it works - both ways. – Poul Bak Sep 06 '22 at 10:16
  • 1
    @PoulBak is correct, and also you've created Language value with double double-quotes but you did not do the same for location. – Helio Sep 06 '22 at 10:20
  • Does this answer your question? [How do I turn a C# object into a JSON string in .NET?](https://stackoverflow.com/questions/6201529/how-do-i-turn-a-c-sharp-object-into-a-json-string-in-net) – Charlieface Sep 06 '22 at 13:06

1 Answers1

0

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"
    }
  ]
}
Serge
  • 40,935
  • 4
  • 18
  • 45