System.Text.Json.JsonSerializer.Serialize adds \u0022

Viewed 4728

How can I set JsonSerializer to not add "\u0022" to string for EventData property? Because I get:

{"Id":5,"CreateDate":"2021-04-21T05:26:30.9817284Z","EventData":"{\u0022Id\u0022:1,\u0022Email\u0022:\u0022test@test.test\u0022}"}

I will never deserialize EventData, it must be readable. And I want:

{"Id":5,"CreateDate":"2021-04-21T05:26:30.9817284Z","EventData":"{Id:1,Email:test@test.test}"}

My code:

public class EmailSent
{
    public int Id { get; set; }
    public string Email { get; set; }
}

public class UserCreated
{
    public int Id { get; set; }
    public DateTime CreateDate { get; set; }
    public string EventData { get; set; }
}

var emailSent = new EmailSent
{
    Id = 1,
    Email = "test@test.test"
};

var userCreated = new UserCreated
{
    Id = 5,
    CreateDate = DateTime.UtcNow,
    EventData = JsonSerializer.Serialize(emailSent) // I will never deserialize it
};

string result = JsonSerializer.Serialize(userCreated);
3 Answers

You can use, for example, UnsafeRelaxedJsonEscaping:

var serializeOptions = new JsonSerializerOptions
{
    WriteIndented = true,
    Encoder = System.Text.Encodings.Web.JavaScriptEncoder.UnsafeRelaxedJsonEscaping
    };

string json = JsonSerializer.Serialize(userCreated, serializeOptions);

This will produce the following output:

{
  "Id": 5,
  "CreateDate": "2021-04-21T07:49:23.4378969Z",
  "EventData": "{\"Id\":1,\"Email\":\"test@test.test\"}"
}

Reference: How to customize character encoding with System.Text.Json. Please read the caution there:

Caution

Compared to the default encoder, the UnsafeRelaxedJsonEscaping encoder is more permissive about allowing characters to pass through unescaped: (...)

This happens because JsonSerializer.Serialize() is invoked more than once.

You can specify 'JSONSerializerOptions' Encoder equal to JavaScriptTenCoder. Create(new TextEncoderSettings(UnicodeRanges.All)) like this

public static string ToString(this object str)
{
    try
    {
         string sResult = JsonSerializer.Serialize(str, new JsonSerializerOptions{WriteIndented = true, Encoder = JavaScriptEncoder.Create(new TextEncoderSettings(System.Text.Unicode.UnicodeRanges.All))});
         return sResult;
    }
}
Related