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
}
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With