Skip to content

Instantly share code, notes, and snippets.

@ProbablePrime
Created October 15, 2021 07:05
Show Gist options
  • Save ProbablePrime/b0c6a210b423a83a6ff86b93e8380484 to your computer and use it in GitHub Desktop.
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.
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