我根据用户提供的预订号码从我的ASP.NET Web API请求预订信息。我的问题是,如果预订编号不存在,Web API仍然返回一个对象,但值为null
。如何检查返回的JSON对象是否为null
?
HttpClient
请求:
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
}
示例返回JSON对象:
{
"BookingRef": null,
"City": null,
"Company": null,
"Country": null,
"CustomerAddress": null,
"CustomerFirstName": null,
"CustomerPhoneNumber": null,
"CustomerSurname": null,
"Entrance": null
}
答案 0 :(得分:2)
一种选择是在属性上使用后期绑定:
var result = JsonConvert.DeserializeObject(jsonMessage, typeof(TOutput));
if (((dynamic)result).BookingRef == null)
{
// Returning null - do whatever is appropriate
return null;
}
else
{
return (TOutput)result;
}