Created
October 15, 2021 07:05
-
-
Save ProbablePrime/b0c6a210b423a83a6ff86b93e8380484 to your computer and use it in GitHub Desktop.
C#'s System.Text.Json has weird handling for quotes. This makes it behave more like Newtonsoft.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Text.Encodings.Web; | |
using System.Text.Json; | |
namespace JSONStuff | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var options = new JsonSerializerOptions | |
{ | |
Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping, | |
WriteIndented = true | |
}; | |
var stringWithQuotes = @" ""Cheese"" is cool"; | |
var escapedStringWithQuotes = JsonSerializer.Serialize<string>(stringWithQuotes, options); | |
Console.WriteLine(escapedStringWithQuotes); | |
var unescapedStringWithQuotes = JsonSerializer.Deserialize<string>(escapedStringWithQuotes, options); | |
Console.WriteLine(unescapedStringWithQuotes); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment