1. System.Text.Json vs Newtonsoft.Json Comparison
`System.Text.Json` was built from the ground up to leverage modern C# features like `Span<T>`, `ReadOnlySpan<byte>`, and `Utf8JsonReader`. By processing UTF-8 bytes directly without converting them to intermediate C# strings, it eliminates heap memory allocations.
using System.Text.Json;
using System.Text.Json.Serialization;
public class UserDto
{
[JsonPropertyName("user_id")]
public int Id { get; set; }
[JsonPropertyName("full_name")]
public string Name { get; set; } = string.Empty;
}
// High-performance deserialization
string jsonString = "{\"user_id\": 101, \"full_name\": \"Sarah Conner\"}";
UserDto? user = JsonSerializer.Deserialize<UserDto>(jsonString);2. Configuring Global JsonSerializerOptions
By default, `System.Text.Json` enforces strict case-sensitive property matching and uses PascalCase output. Configure global `JsonSerializerOptions` to handle camelCase naming conventions and ignore null values.
var options = new JsonSerializerOptions
{
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull,
WriteIndented = true // Pretty-print JSON output
};
string prettyJson = JsonSerializer.Serialize(user, options);3. Implementing a Custom JsonConverter<T>
For non-standard data types or legacy API date string formats, override `JsonConverter<T>` to control byte-level reading and writing.
public class DateTimeCustomConverter : JsonConverter<DateTime>
{
public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options)
{
return DateTime.Parse(reader.GetString()!);
}
public override void Write(Utf8JsonWriter writer, DateTime value, JsonSerializerOptions options)
{
writer.WriteStringValue(value.ToString("yyyy-MM-dd HH:mm:ss"));
}
}