What gets escaped
| Character | Default encoder | UnsafeRelaxedJsonEscaping |
|---|---|---|
" | " | \" |
\ | \\ | \\ |
| Line feed, carriage return, tab, backspace, form feed | \n, \r, \t, \b, \f | the same |
| Other control characters | \u0001 style | the same |
< > & ' + ` | < style | as they are |
Non-ASCII letters (é, ä¸) | é style | as they are |
| Emoji and other characters above U+FFFF | a surrogate pair, 😀 | the same |
| A lone surrogate (broken UTF-16) | � | � |
Both outputs are valid JSON and read back as the same string. The default encoder is stricter so the JSON is safe to embed in HTML and <script> blocks. Use the relaxed encoder only when the JSON never ends up in a web page; for readable non-ASCII text alone, JavaScriptEncoder.Create(UnicodeRanges.All) is the safer choice. The forward slash is never escaped by System.Text.Json.
JSON in C# source code
- Raw string literals (C# 11, .NET 7 and later) are the easiest: nothing inside is escaped. The opening and closing quotes need more double quotes than the longest run inside, so JSON containing
"""gets four. A multi-line raw literal drops the indentation of the closing quotes from every line. - Verbatim literals (
@"...") only double the double quotes. Backslashes stay single, which also makes them handy for Windows paths. - Regular literals escape
\",\\and control characters. C# also treats U+0085, U+2028 and U+2029 as line breaks, so they must be escaped too; the page does that. - A line break inside a verbatim or raw literal is whatever the source file uses,
\nor\r\n. If the exact line endings matter, use the regular literal. - For an interpolated raw string with JSON braces, start it with
$$"""; then{is a brace and{{name}}is a hole.
FAQ
Why does System.Text.Json write " instead of \"?
The default encoder escapes everything that is unsafe in HTML, and the double quote is one of those characters. " and \" mean the same in JSON.
How do I put JSON in a C# string?
Use a raw string literal (C# 11): wrap the JSON in three or more double quotes and nothing inside needs escaping. In older C#, use a verbatim literal (@"...") with every double quote doubled, or a regular literal with \" and \n escapes.
How do I stop System.Text.Json escaping non-ASCII characters?
Set Encoder = JavaScriptEncoder.Create(UnicodeRanges.All) in JsonSerializerOptions. HTML-sensitive characters stay escaped. UnsafeRelaxedJsonEscaping goes further and leaves those alone too.
Is my text uploaded?
No. Both the escaping and the C# literals are generated in your browser.