0

I serialize and save a lot of data with the help of the following code

using var stream = File.Create("file.json");
await System.Text.Json.JsonSerializer.SerializeAsync(stream, data, new JsonSerializerOptions
            {
                WriteIndented = true
            });

But the data is saved as follows

{
  "MyProperty": "\u0633\u0644\u0627\u0645",
  "MyProperty2": "\u0634\u0633\u06CC\u0634\u0633\u06CC"
}

How can I set the encoding to UTF-8 or Unicode when saving?

Atena
  • 109
  • 2
  • 9
  • 1
    A simple documentation search yielded https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-character-encoding – fredrik Jan 04 '22 at 08:10
  • This is nothing to do with `File.Create` (which doesn't have a concept of encoding: it deals with raw bytes) or indeed encoding (since you're able to view the correct characters in the file). This is about the JSON serializer deciding to turn certain Unicode characters into their equivalent JSON escape sequences. Once you figure this out, it's obvious that the solution is somewhere in the `JsonSerializer` settings. I've linked your question to one which asked the same thing, and has a couple of good answers. Please read them all -- `UnsafeRelaxedJsonEscaping` is `Unsafe` for a reason – canton7 Jan 04 '22 at 08:48

0 Answers0