【发布时间】:2023-03-22 18:47:01
【问题描述】:
我根据用户提供的预订号从我的 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
}
【问题讨论】:
-
为什么要使用泛型对象,而不是定义可以强使用的对象?
-
您找到解决方案了吗?我有同样的问题。它对我来说也引发了反序列化部分
标签: c# asp.net-mvc json asp.net-mvc-4 asp.net-web-api