Home > database >  Go from nullable to non-nullable after ReadFromJsonAsync
Go from nullable to non-nullable after ReadFromJsonAsync

Time:12-31

ReadFromJsonAsync method returns nullable T. Here is a code sample:

private async Task<T> Get<T>(Uri url, CancellationToken cancellationToken)
{
    using HttpResponseMessage response = await _httpClient.GetAsync(url, cancellationToken);

    T? body = await response.Content.ReadFromJsonAsync<T>(cancellationToken: cancellationToken);

    return body ?? throw new Exception();
}

I want my method to return non-nullable value.

I am wondering when ReadFromJsonAsync will return null. No matter how I have tried I was still getting instance of T with all properties equal null. So I hoped that it would be safe to write code like this:

    return (T)body;

But now I am getting a warning Converting null literal or possible null value to non-nullable type.

What about this, is it a good idea:

    return body!;

CodePudding user response:

ReadFromJsonAsync is a utility method that gets the response's content stream and then passes that to JsonSerializer.DeserializeAsync.

DeserializeAsync is defined as returning a nullable value, because it might return null. It will do so in the case where you attempt to deserialize a null JSON value.

If you don't expect those, then you can use ! to just ignore the warning. But the safest way would be to indeed check for null and either throw an exception or return a fallback balue.

  • Related