我有以下数据:
{"data":{"id":"7IaWnXo","title":null,"description":null,"datetime":1397926970,"type":"image/png","animated":false,"width":60,"height":60,"size":1277,"views":0,"bandwidth":0,"favorite":false,"nsfw":null,"section":null,"deletehash":"KYIfVnHIWWTPifh","link":"http://i.imgur.com/7IaWnXo.png"},"success":true,"status":200}
我正在尝试将其序列化为:
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;}
}
我得到:
An exception of type 'System.InvalidOperationException' occurred in System.Web.Extensions.dll but was not handled in user code
Additional information: Cannot convert null to a value type.
我做错了什么?
最佳答案
在您的 JSON 数据中:nsfw
为空。
但是在ImageInfo
结构,nsfw
被定义为 boolean
(它不能为空,只能为 true
或 false
)
你有 2 种可能性。
- 如果您有权访问 JSON 数据,则不允许
null
对于nsfw
. - 使用可为空的 bool 值:
public bool? nsfw {get; set;}
如果您选择第二个选项,这将使您拥有 true
, false
或 null
作为 nsfw
的值你不会再有这个错误了。
两者都是 Nullable<bool>
和 bool?
是相同的语法。
有关 Nullable Types 的更多信息
关于c# - JavascriptSerializer 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23173132/