-
Hi Team, I have this snippet using System.Diagnostics;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Example;
public class Program
{
public static void Main(string[] args)
{
string json = "{\"name\": null}";
// I would love this to throw an exception because Name should not be null.
SomeClass sc = JsonSerializer.Deserialize<SomeClass>(json)!;
Debug.Assert(sc.Name != null);
}
}
public class SomeClass
{
// [Required] // this didn't help to enforce that this property can't be null.
// [NotNull] // this didn't help to enforce that this property can't be null.
[JsonPropertyName("name")]
public string Name { get; }
[JsonConstructor]
public SomeClass(string name)
{
this.Name = name;
}
} and I'm looking for a way to forbid cc @dotnet/area-system-text-json |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 7 replies
-
Maybe adding the null check in the ctor is ok for you?
Or you can use the IJsonOnDeserialized interface:
But I agree, having the [Required] attribute would have been the greatest option. Hopefully the [Required] attribute will be added in a future release. |
Beta Was this translation helpful? Give feedback.
-
This is now possible in .NET 7: Update: The required properties above does not solve the problem. However, there are some limited support for non-nullable reference type enforcement in .NET 9: |
Beta Was this translation helpful? Give feedback.
This is now possible in .NET 7:
https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/required-properties
Update: The required properties above does not solve the problem. However, there are some limited support for non-nullable reference type enforcement in .NET 9:
https://learn.microsoft.com/en-us/dotnet/standard/serialization/system-text-json/nullable-annotations