.NET users have largely relied on Newtonsoft.Json
and other popular JSON libraries, which continue to be good choices. Newtonsoft.Json
uses .NET strings as its base datatype, which is UTF-16 under the hood.
The System.Text.Json
is built-in as part of the shared framework for .NET Core 3.0 and later versions.
For earlier framework versions, install the System.Text.Json NuGet package.
To serialize to UTF-8, call the JsonSerializer.SerializeToUtf8Bytes
method as shown below.
public class Customer
{
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
};
public static void Example1()
{
Customer customer = new Customer()
{
Name = "Mark",
Age = 40,
Address = "22 Ashdown"
};
byte[] jsonUtf8Bytes = JsonSerializer.SerializeToUtf8Bytes(customer);
Console.WriteLine(jsonUtf8Bytes);
}
To pretty-print the JSON output, set JsonSerializerOptions.WriteIndented
to true
as shown below.
public class Customer
{
public string Name { get; set; }
public int Age { get; set; }
public string Address { get; set; }
};
public static void Example2()
{
Customer customer = new Customer()
{
Name = "Mark",
Age = 40,
Address = "22 Ashdown"
};
var options = new JsonSerializerOptions
{
WriteIndented = true
};
var jsonUtf8Bytes = JsonSerializer.Serialize(customer, options);
Console.WriteLine(jsonUtf8Bytes);
}