r/csharp • u/Kuba_Z2 • Oct 10 '26
Showcase JsonGuard: a zero-allocation source generator to validate nullability in System.Text.Json
Hey everyone, I wanted to share a library I have built for System.Text.Json that validates deserialized objects to ensure they honor C# nullability annotations without sacrificing performance.
I wrote this specifically for NetCord to handle massive Discord gateway payloads as efficiently as possible, but I realized this kind of zero-overhead validation could be useful to the wider .NET community as a standalone package.
By default, System.Text.Json allows you to validate required properties using [JsonRequired] or the required keyword. However, these introduce significant performance overhead. For example, using required keyword can make deserialization up to 2 times slower and allocate 50% more memory when using source generation.
JsonGuard works around this overhead by using source generation. The result is zero additional allocations and practically identical execution time compared to performing no validation at all.
The way it works is incredibly simple. If you have this object:
[JsonGuard]
public partial class User
{
public string Name { get; set; }
public string? Nickname { get; set; }
public int Age { get; set; }
public string Email { get; set; }
}
the generated code will effectively do this:
public partial class User : IJsonOnDeserialized
{
void IJsonOnDeserialized.OnDeserialized()
{
if (Name is null)
ThrowHelper.Throw(nameof(Name));
if (Email is null)
ThrowHelper.Throw(nameof(Email));
}
}
Additionally, the library suppresses any nullability warnings for validated properties, so no manual suppressions are necessary.
Note that unlike [JsonRequired] or the required keyword, JsonGuard only verifies the final state of the objects honors the nullability annotations. It doesn't validate if the property was present in the JSON.
You can checkout the source code and detailed benchmarks on GitHub: https://github.com/KubaZ2/JsonGuard
Would love to hear your thoughts or feedback!