Search code examples
c#json.net-coreexceptionsystem.text.json

How to force System.Text.Json serializer throw exception when property is missing?


Json.NET behaviour could be defined by attributes: either use default or just throw an exception if json payload does not contain required property.

Yet System.Text.Json serializer silently does nothing.
Having class:

public sealed class Foo
{
    [Required]
    public int Prop {get;set;} = 10;
}

and deserializing empty object:

JsonSerializer.Deserialize<Foo>("{}");

I simply get an instance of Foo with Prop=10. I could not find any setting in JsonSerializerOptions to force it throw an exception. Is it possible?


Solution

  • System.Text.Json doesn't throw an exception if no value is received for one of the properties of the target type. You need to implement a custom converter.

    Reference: https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json-migrate-from-newtonsoft-how-to#required-properties