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

标签 c# asp.net-mvc json asp.net-mvc-4 asp.net-web-api

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

相关文章:

c# - 到处查找枚举转换为字符串

asp.net-mvc - 如何在 .NET MVC 2 中实现正确的 HTTP 错误处理?

c# - 使用 session ID 将消息添加到 IAsyncCollector 主题输出

c# - 关于使用 Enumerable.Range 与传统 for 循环的 foreach 的思考

c# - 访问 ASP.Net MVC 中的私有(private)全局变量

jquery - Angularjs + ASP.NET MVC + ASP.NET Web API

java返回带有两个json数组的json对象

java - 如何向php发送数据?

php - 将 json 数据转换为 HTML 表格

c# - DropDownList 不回发,即使设置了 AutoPostBack