0

I have a custom JSON writer that uses UTF8JsonWriter.

No problem sending over internet, writing to disk, and reading back.

But now I need some beautifying for console, so I don't want the Asian language character escaping (No \u1234 something...). I just want them to look like as in JSON visualizer of Visual Studio

enter image description here

So I wonder if there is something like System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping

for UTF8JsonWriter and/or JsonWriterOptions.

I'm not using NewtonSoft's JSON library.

Tried things like

byte[] bytesConverted = Encoding.Convert(Encoding.UTF8, Encoding.Unicode, bytes);
string s8 = Encoding.UTF8.GetString(utf8bytes, 0, utf8bytes.Length);
string s16 = Encoding.Unicode.GetString(utf16bytes, 0, utf16bytes.Length);

but had no luck.

Here is the custom json writer

    public static void WriteNodes(Utf8JsonWriter w, IEnumerable<Node> nodes)
    {
        w.WriteStartObject();
        w.WriteStartArray("nodes");
        foreach (Node n in nodes)
        {
            w.WriteStartObject();
            w.WriteString("id", n.Id.ToString());
            w.WriteStartObject("properties");
            foreach (var p in n.Properties.Keys)
            {
                w.WriteStartObject(p);
                var pVal = n.Properties[p];
                pVal.Write(w);
                w.WriteEndObject();
            }
            w.WriteEndObject();
            w.WriteEndObject();
        }
        w.WriteEndArray();
        w.WriteEndObject();
    }

And this is pipe listener

public async void pipeThreadFunc()
{
  while (true)
  {
    using (var server = new NamedPipeServerStream(PipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Message, PipeOptions.Asynchronous))
    {
      Log?.Invoke(this, "Waiting for Connection");
      await server.WaitForConnectionAsync();
      if (server.IsConnected)   Log?.Invoke(this, "Connected");
      using (var streamReader = new StreamReader(server))
      {
        MemoryStream ms = new MemoryStream();
        byte[] buffer = new byte[0x1000];
        do { ms.Write(buffer, 0, server.Read(buffer, 0, buffer.Length)); }
        while (!server.IsMessageComplete);
        string query = Encoding.UTF8.GetString(ms.ToArray());
        var nodesFound = await LookUpDBAsync(query);

        // Can we please turn off CJK escaping here?
        //
        var writerOptions = new JsonWriterOptions { Indented = true };

        byte[] bytes;
        string resJson = "";
        using (var ms_write = new MemoryStream())
        using (var w = new Utf8JsonWriter(ms_write, writerOptions))
        {
          WriteNodes(w, nodesFound);  //json writer above
          w.Flush();
          ms_write.Close();                         
          bytes = ms_write.ToArray();
        }
        byte[] bytesConverted = Encoding.Convert(Encoding.UTF8, Encoding.Unicode, bytes);

        resJson = Encoding.UTF8.GetString(bytes);

        // Write escaped string as intended
        await server.WriteAsync(bytes, 0, bytes.Length);

        /* failed attempts -->
        byte[] utf8bytes = Encoding.UTF8.GetBytes(resJson);
        byte[] utf16bytes = Encoding.Unicode.GetBytes(resJson);
        string s8 = Encoding.UTF8.GetString(utf8bytes, 0, utf8bytes.Length);
        string s16 = Encoding.Unicode.GetString(utf16bytes, 0, utf16bytes.Length);
        <-- */
        string ss = Encoding.Unicode.GetString(bytesConverted, 0, bytesConverted.Length);

        // Hope this writes unescaped string
        Log?.Invoke(this, $"[{query}] = {ss}");

     }
     if (server.IsConnected)
     {
       server.Disconnect();
       Log?.Invoke(this, "Disconnected");
     }
   }
 }

}

public event EventHandler<string> Log;
Jeffrey Goines
  • 935
  • 1
  • 11
  • 30
  • _"I wonder if there is something like `System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping`"_ - Can I ask what's wrong with just using that? It seems to work fine for me when I used it with `Utf8JsonWriter`. – ProgrammingLlama May 15 '21 at 16:10
  • [Without `UnsafeRelaxedJsonEscaping` encoder](https://i.stack.imgur.com/gW1Kw.png) vs [with `UnsafeRelaxedJsonEscaping` encoder](https://i.stack.imgur.com/pNsUQ.png). Please provide code to demonstrate this not working. – ProgrammingLlama May 15 '21 at 16:16
  • @Llama This is a .NET framework 4.7.2 project (without any Nuget packages installed) and System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping doesn't seem to exist. Couldn't add a reference to the assembly (Quick actions and refactorings etc) I would install it if I have to, but I just prefer not to install Nuget packages. – Jeffrey Goines May 15 '21 at 23:19
  • 1
    *This is a .NET framework 4.7.2 project (without any Nuget packages installed)* -- but you need to install https://www.nuget.org/packages/System.Text.Json/ to use `System.Text.Json` in .NET Framework, don't you? And that package has a dependency upon https://www.nuget.org/packages/System.Text.Encodings.Web/ which includes `System.Text.Encodings.Web.JavaScriptEncoder`, so are you sure you don't have it? – dbc May 16 '21 at 03:39
  • @dbc Quick action/factoring suggests two different options. The first one is to install older version of System.Text.Json and no Nuget package is involved (seem to be included in VS2019 community). The second one however is installation by Nuget – Jeffrey Goines May 16 '21 at 03:59
  • 1
    My previous question was why you were against installing the System.Text.Json NuGet package, but I've just tried using .NET Framework 4.7.2 (the version of VS doesn't make a difference here) and without installing System.Text.Json from NuGet, it's certainly not available as part of the .NET Framework. Is it possible you've already installed it via NuGet as a dependency? – ProgrammingLlama May 16 '21 at 05:27
  • @Llama Oh it's just because of the size of the solution files. The one with Nuget occupies 5-6 times of disk space and when the internet connection is slow backup fails etc... This is the only point I need Nuget so... – Jeffrey Goines May 16 '21 at 10:02

0 Answers0