Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
}
like image 658
Romeo Avatar asked Nov 01 '22 18:11

Romeo


1 Answers

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;
}
like image 73
Lars Kemmann Avatar answered Nov 15 '22 04:11

Lars Kemmann