Replacing \u0022 with \" in Serialized JSON

Download full source code.

tl;dr

If you see output in your JSON that looks like this -

{
  "Messages": [
    {
      "MessageBody": "{\u0022Name\u0022:\u0022Alan Adams\u0022,\u0022Age\u0022:11}",

Pass JsonSerializerOptions with -

Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping

to your Serialize(..) method.

The problem

This isn’t really a problem, more of a readability issue. If you serialize an object that has a nested serialized object to JSON, the serializer will escape all the double quotes (and other unsafe characters) in the nested object.

Why might you have a nested serialized object? If you are using a message queue, you will likely have a message type with info about the message - source, id, timestamps, etc. It will also have a message body. The message body will be a serialized version of the object you are sending.

For example, let’s say you have a message type like this -

public class QueueEvent
{
    public Message[] Messages { get; set; }
}

public class Message
{
    public Guid MessageId { get; set; }
    public string MessageBody { get; set; } // this will have a serialized object
    public string MessageSource { get; set; }
    public string SentTimestamp { get; set; }
    public string SenderId { get; set; }
}

The message body is a serialized version of this -

public class Person
{
    public string Name { get; set; }
    public int Age { get; set; }
}

When you serialize an object to JSON, the output will look something like this -

{
  "Messages": [
    {
      "MessageId": "3c631024-194f-4b13-bb62-a32d83c511e0",
      "MessageBody": "{\u0022Name\u0022:\u0022Alan Adams\u0022,\u0022Age\u0022:11}",
      "MessageSource": "Somewhere",
      "SentTimestamp": "12/11/2023 9:47:47 PM",
      "SenderId": "12345"
    }
  ]
}

Notice the double quotes in the serialized value of the MessageBody property are gone and replaced with \u0022. This makes it a bit harder to read.

The fix

Note that the fix makes the encoded JSON less safe, and Microsoft has a warning about this in the docs.

To get back the familiar \", you need to create a JsonSerializerOptions with an Encoder set to JavaScriptEncoder.UnsafeRelaxedJsonEscaping.

var jsonSerializerOptions = new JsonSerializerOptions
{
    WriteIndented = true, // not necessary, but more readable
    Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
};

Then pass the options to the Serialize(..) method -

string serializedQueueEvent = JsonSerializer.Serialize(queueEvent, jsonSerializerOptions);

Now the output will be easier to read-

{
  "Messages": [
    {
      "MessageId": "72fff2a2-5a39-4dab-aa28-3bde4a374dd2",
      "MessageBody": "{\"Name\":\"Alan Adams\",\"Age\":11}",
      "MessageSource": "Somewhere",
      "SentTimestamp": "12/12/2023 9:47:47 AM",
      "SenderId": "12345"
    }
  ]
}

Download full source code.

comments powered by Disqus

Related