C# JavascriptSerializer异常
我有以下数据: {“数据”:{“id”:“7IaWnXo”,“title”:null,“description”:null,“datetime”:1397926970,“type”:“image/png”,“animated”:false,“width”:60,“height”:60,“size”:1277,“views”:0,“带宽”:0,“favorite”:false,“nsfw”:null,“section”:null,“deletehash”:“KYIfVnHIWWTPifh”,“link”:http://i.imgur.com/7IaWnXo.png},“成功”:真,“状态”:200} 我正试图将其序列化为:C# JavascriptSerializer异常,c#,exception,javascriptserializer,C#,Exception,Javascriptserializer,我有以下数据: {“数据”:{“id”:“7IaWnXo”,“title”:null,“description”:null,“datetime”:1397926970,“type”:“image/png”,“animated”:false,“width”:60,“height”:60,“size”:1277,“views”:0,“带宽”:0,“favorite”:false,“nsfw”:null,“section”:null,“deletehash”:“KYIfVnHIWWTPifh”,“li
public struct ImageInfoContainer
{
public ImageInfo data {get; set;}
bool success { get; set; }
string status { get; set; }
}
public struct ImageInfo
{
public string id {get; set;}
public string title { get; set; }
public string url { get; set; }
public string description {get; set;}
public string datetime {get; set;}
public string type {get; set;}
public string animated {get; set;}
public int width {get; set;}
public int height {get; set;}
public int size {get; set;}
public int views {get; set;}
public int bandwidth {get; set;}
public bool favourite {get; set;}
public bool nsfw {get; set;}
public string section {get; set;}
public string deletehash {get; set;}
public string link {get; set;}
}
我得到:
System.Web.Extensions.dll中发生“System.InvalidOperationException”类型的异常,但未在用户代码中处理
其他信息:无法将null转换为值类型
我做错了什么?在JSON数据中:
nsfw
为空。但是在
ImageInfo
struct中,nsfw
被定义为boolean
(它不能为空,只能true
或false
)
你有两种可能
- 如果您有权访问JSON数据,请不要为
允许nsfw
李>null
- 使用可空bool:
公共bool?nsfw{get;set;}
true
、false
或null
作为nsfw
的值,并且您将不再有此错误
Nullable
和bool?
都是相同的语法。有关“nsfw”的更多信息:空的应为
真的
或假的
部分
不应为空。