gpt4 book ai didi

c# - 空对象不能转换为值类型

转载 作者:行者123 更新时间:2023-11-30 16:58:25 25 4
gpt4 key购买 nike

我根据用户提供的预订编号从我的 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
}

最佳答案

一种选择是对属性使用后期绑定(bind):

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

关于c# - 空对象不能转换为值类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25278399/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com