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

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:\[email protected]\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:[email protected]}"}

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 = "[email protected]"
};

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

string result = JsonSerializer.Serialize(userCreated);


Solution 1:[1]

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\":\"[email protected]\"}"
}

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: (...)

Solution 2:[2]

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

Solution 3:[3]

You can specify 'JSONSerializerOptions' Encoder equal to JavaScriptTenCoder. Create(new TextEncoderSettings(UnicodeRanges.All)) like imageenter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 tymtam
Solution 2 Daniel Hat
Solution 3 Chenxianda