1
A little bit of context:
I have a C# 8 project using a resource called Nullable Reference Types. When this feature is enabled in the project settings (csproj) compiler treats all class instances as unallowable unless they are declared explicitly unattainable.
For example:
string str1 = null; // isso é inválido
string? str2 = null; // isso é válido
However I noticed that this feature exists only at compile time, if the type variable string
is initialized by an external code, it can still receive the value null
at runtime.
So I have my classes declared with non-avoidable properties, I will use any example here:
class User
{
[JsonPropertyName("name")]
public string Name { get; set; } = "";
[JsonPropertyName("email")]
public string Email { get; set; } = "";
}
In that class I hope the properties Name
and Email
are never null
, but if I get one JSON in format {"name": null, "email": null}
, and deserialize it in an instance of that class with the library System.Text.Json, i will have a user with name and email equal to null
.
I would like to know what can be done to prevent this kind of behavior. Until then I thought to implement all getters and setters manually to prevent them from receiving null
, in the following style:
class User
{
private string name = "";
[JsonPropertyName("name")]
public string Name
{
get { return name; }
set { name = value ?? ""; }
}
private string email = "";
[JsonPropertyName("email")]
public string Email
{
get { return email; }
set { email = value ?? ""; }
}
}
But this seems to me unnecessarily verbose and repetitive. I wonder if there is a more practical standard approach to this problem.
the behavior you exemplified is this same, what you can do is a kind of own to make this aspect for you, have to take a look at the library in that part
– novic
the solution may be: https://docs.microsoft.com/pt-br/dotnet/standard/serialization/system-text-json-how-to#exclude-all-null-value-properties
– novic