Deserialize JSON with null Safety in C#

Asked

Viewed 52 times

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.

  • 1

    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

  • the solution may be: https://docs.microsoft.com/pt-br/dotnet/standard/serialization/system-text-json-how-to#exclude-all-null-value-properties

1 answer

0


  • This solves the problem with deserialization, pity that properties are still vulnerable to other libraries, and devs who are not aware of this behavior.

  • Look I would also trigger a validation @Julio. I would criticize even more the past values. Although I vulnerable to other libraries did not understand.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.