0

I am wracking my brain about this and can't figure out why or how to fix it.

This test should pass:

[Test]
public void EncodingTest()
{
    var json = JsonSerializer.Serialize("\"");

    Assert.AreEqual("\\\"", json);
}

but it doesn't. It's saying that a double-quote " in a string should be translated to \", which is (fairly universally) the preferred serialization for this character. (See string at json.org.)

But what's actually happening is that it gets encoded as \u0022 which is the unicode code-point for it.

I understand that \u0022 is allowed, but it's horribly unreadable.

I've found this question which pointed me to

None of what I've read says how to get the JsonSerializer to just escape it (like every other serializer I've seen).

gregsdennis
  • 7,218
  • 3
  • 38
  • 71
  • 1
    You could check to see whether `System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping` fixes things for you. See: [dotnet core System.Text.Json unescape unicode string](https://stackoverflow.com/q/58003293/3744182). – dbc Jul 12 '20 at 16:06
  • Yes, that works. See https://dotnetfiddle.net/688IOt. Do note that the JSON generated is `"\""` (because JSON string literals are always surrounded by double quotes) so your assert needs to look like `Assert.AreEqual("\"\\\"\"", json);` – dbc Jul 12 '20 at 16:10
  • 1
    I thought I had tried that. Works now anyway. Thanks. – gregsdennis Jul 12 '20 at 22:38

0 Answers0