Romeo
Romeo

Reputation: 1831

Null object cannot be converted to a value type

I'm requesting a booking information from my ASP.NET Web API depending on the booking number given by the user. My issue is, if the booking number does not exist the Web API is still returning an object but the values are null. How can I check if the returned JSON object is null?

HttpClient request:

 var response = await client.PostAsJsonAsync(strRequestUri, value);

if (response.IsSuccessStatusCode)
{
    string jsonMessage;
    using (Stream responseStream = await response.Content.ReadAsStreamAsync()) // put response content to stream
    {
        jsonMessage = new StreamReader(responseStream).ReadToEnd(); 
    }
    // I'm getting the error from here when I'm casting the json object to my return type.
    return (TOutput)JsonConvert.DeserializeObject(jsonMessage, typeof(TOutput)); // TOutput is a generic object
}

sample returned JSON object:

{
    "BookingRef": null,
    "City": null,
    "Company": null,
    "Country": null,
    "CustomerAddress": null,
    "CustomerFirstName": null,
    "CustomerPhoneNumber": null,
    "CustomerSurname": null,
    "Entrance": null
}

Upvotes: 5

Views: 14730

Answers (1)

Lars Kemmann
Lars Kemmann

Reputation: 5674

One option is to use late binding on the property:

var result = JsonConvert.DeserializeObject(jsonMessage, typeof(TOutput));
if (((dynamic)result).BookingRef == null)
{
    // Returning null - do whatever is appropriate
    return null;
}
else
{
    return (TOutput)result;
}

Upvotes: 2

Related Questions