1

Using Non-Nullable Reference Types is great, but there seems to be no built-in support for enforcing Non-Nullability when compiling a class with nullable=enable and using something like XML or JSON deserialization. I know it's just compiler attributes that get set, but isn't there any easy way to make sure a deserialized object didn't have some (maybe nested!) properties that shouldn't be null, but are?

If you explicitly set a non-nullable reference property to null in your JSON, Newtonsoft.JSON and System.Text.Json will happily use that as a property value. I'm using Records everywhere to get around annoying initalization procedure and it works for serializing/deserializing, but it never actually enforces that deserialized properties are not null. :(

I don't want to check for null everywhere I use the properties - that's what I'm using Non-Nullable Reference Types for in the first place!

I'm thinking about writing a recursive reflection function to validate objects retrieved this way, but surely somebody must have already though of that problem?

AyCe
  • 727
  • 2
  • 11
  • 30
  • With Json.NET, you could use reflection to check for null non-nullable reference properties in an [`[OnDeserialized]`](https://www.newtonsoft.com/json/help/html/SerializationCallbacks.htm) callback added by a custom contract resolver. See [How to use .NET reflection to check for nullable reference type](https://stackoverflow.com/q/58453972). [This answer](https://stackoverflow.com/a/64133814) by [Rico Suter](https://stackoverflow.com/users/876814/rico-suter) links to a library the answerer wrote that offers an extension method `EnsureValidNullability()`. – dbc May 13 '22 at 15:24
  • For System.Text.Json you could add the callback by implementing the [`IJsonOnDeserialized`](https://learn.microsoft.com/en-us/dotnet/api/system.text.json.serialization.ijsonondeserialized?view=net-6.0) interface. – dbc May 13 '22 at 15:27
  • @dbc Thanks, but the 2 callback methods mean that you have to write code for them yourself in each type, I'd like to avoid that. For anyone else finding this question: There is also this lib: https://github.com/SimonCropp/NullabilityInfo Rico Suters lib seems to be the best choice, though I think this functionality should really be available by default. – AyCe May 15 '22 at 15:49
  • *you have to write code for them yourself in each type, I'd like to avoid that* -- you can used a custom contract resolver to add a standard callback to each JsonObjectContract. – dbc May 15 '22 at 16:39

0 Answers0