【问题标题】:Null object cannot be converted to a value typeNull 对象不能转换为值类型
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

  • 嗨 Lars,我在执行 JsonConvert.DeserializeObject(jsonMessage, typeof(TOutput)) 时已经收到错误消息。另外我忘了提到 TOutput 是一个通用对象
  • 嗨@rcadaoas,我确实认为TOutput 很可能是通用的。 :) 你能具体说明你得到的“错误”吗? DeserializeObject 调用是否引发异常?如果调用只是返回一个带有一堆空值的对象,那么上面的方法应该仍然有效。否则,您可以使用 try-catch 块包装 DeserializeObject 调用。
  • 嗨,拉斯。是的,DeserializeObject 正在抛出错误“Null 对象无法转换为值类型”。是的,我已经用 try catch 块包装了它。
  • 好的,但现在我很困惑。您发布的“示例返回的 json 对象”是什么?我认为这是DeserializeObject 调用的结果。如果不是,那 JSON sn-p 显示的是什么?
  • 虽然上面回答了正文中的问题,但并没有解决错误消息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-04-09
  • 2016-10-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多