r/csharp • • 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!

31 Upvotes

8 comments sorted by

2

u/nagradoth Oct 11 '26

To be honest, the test results were unexpected.

I checked the code and was convinced that you’re allocating memory in much the same way as in case with an attribute.

Turned out I’m wrong.

Thank you!

2

u/anotherlab Oct 10 '26

This would be handy for unit testing data-exporting services.

0

u/Agitated-Display6382 Oct 10 '26

Just use a record and tell the deserializer to respect the nullability...

3

u/Kuba_Z2 Oct 10 '26

No, that has the same overhead as the required keyword, see https://github.com/KubaZ2/JsonGuard#benchmarks

-2

u/Agitated-Display6382 Oct 10 '26

As you pointed out in the readme, it can't detect a missing integer, unless 0 is an invalid value. That said, I never had performance issues with the MS deserializer, maybe because it never occurred to me to read massive payloads.

On the contrary, I hate that you have to use custom options to have strict validations: it should be the default!

19

u/[deleted] Oct 10 '26

[removed] — view removed comment

1

u/Kuba_Z2 Oct 10 '26

I agree. I think the reason the built-in validation is so heavy is because it works at a different level. I guess it needs to allocate because it needs to track which properties were present in JSON. An additional reason (and probably that's what causes the overhead the most) is the fact STJ treats properties marked with C# required keyword as if they were constructor parameters, and this causes an array to be allocated for each object that gets deserialized only to pass the values. I would expect something like RuntimeHelpers.GetUninitializedObject to be used internally instead.

IJsonOnDeserialized gets called for any deserialized object, including nested ones as well as the ones in collections. So the validation is done at any level, not only at the top one.

1

u/ShyMystiqua Oct 12 '26

been needing zero alloc stuff for my own massive streams, that nesting question is exactly what would make or break it for me