High-performance JSON API

Raw System.Text.Json

.NET Core 3.0, has shipped with the new System.Text.Json APIs, which provides built-in support for JSON, including reader/writer, read-only DOM, and serializer/deserializer. With the performance, the main improvement to the methods, check and see the typical speedups of up to 2x over Json.NET.

Doing micro-benchmarks to compare System.Text.Json with Json.NET yields the following output:

ScenarioSpeedMemory
Deserialization2x fasterParity or lower
Serialization1.5x fasterParity or lower
Document (read-only)3-5x faster~Allocation free for sizes < 1 MB
Reader2-3x faster~Allocation free (until you materialize values)
Writer1.3-1.6x faster~Allocation free

ASP.NET Core 3.0 includes support for System.Text.Json, which is enabled by default.

Using System.Text.Json directly

For all the samples, make sure you import the following two namespaces:

using System.Text.Json;
using System.Text.Json.Serialization;

Using the serializer

The System.Text.Json the serializer can read and write JSON asynchronously and is optimized for UTF-8 text, making it ideal for REST API and back-end applications.

class WeatherForecast
{
public DateTimeOffset Date { get; set; }
public int TemperatureC { get; set; }
public string Summary { get; set; }
}
string Serialize(WeatherForecast value)
{
return JsonSerializer.ToString(value);
}

By default, a minified JSON is produced. To produce something that is human-readable, you can pass in an instance of JsonSerializerOptions to the serializer. This is also the way you configure other settings, such as handling of comments, trailing commas, and naming policies.

string SerializePrettyPrint(WeatherForecast value)
{
var options = new JsonSerializerOptions
{
WriteIndented = true
};
return JsonSerializer.ToString(value, options);
}

Deserialization works similarly:

 // {
 //      "Date": "2013-01-20T00:00:00Z",
 //      "TemperatureC": 42,
 //      "Summary": "Typical summer in Seattle. Not.",
 // }
 WeatherForecast Deserialize(string json)
 {
     var options = new JsonSerializerOptions
     {
         AllowTrailingCommas = true
     };
     return JsonSerializer.Parse(json, options);
}

The support asynchronous serialization and deserialization:

async Task SerializeAsync(WeatherForecast value, Stream stream)
{
    await JsonSerializer.WriteAsync(value, stream);
}

You can also use custom attributes to control serialization behaviour, for example, ignoring properties and specifying the name of the property in the JSON:

class WeatherForecast
 {
     public DateTimeOffset Date { get; set; }
// Always in Celsius.
 [JsonPropertyName("temp")]
 public int TemperatureC { get; set; }
 public string Summary { get; set; }
// Don't serialize this property.
 [JsonIgnore]
 public bool IsHot => TemperatureC >= 30;
}

Original article can be found here: https://devblogs.microsoft.com/dotnet/try-the-new-system-text-json-apis/