c# - JavascriptSerializer 异常

标签 c# exception javascriptserializer

我有以下数据:

{"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 (它不能为空,只能为 truefalse )

你有 2 种可能性。

  • 如果您有权访问 JSON 数据,则不允许 null对于 nsfw .
  • 使用可为空的 bool 值:public bool? nsfw {get; set;}

如果您选择第二个选项,这将使您拥有 true , falsenull作为 nsfw 的值你不会再有这个错误了。

两者都是 Nullable<bool>bool?是相同的语法。
有关 Nullable Types 的更多信息

关于c# - JavascriptSerializer 异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23173132/

相关文章:

c# - JavaScriptSerializer.Deserialize - 如何更改字段名称

c# - asp.net JavascriptSerializer 可以将空值编码为空字符串吗?

指定通用返回类型的 C# 接口(interface)

c# - 项目集合构建服务锁定我的文件

exception - 我可以将应用程序与真实用户一起使用还是 "Can only call this method on valid test users for your app"

c# - ASP.NET WebService 正在用 XML 标记包装我的 JSON 响应

c# - 在 C# 中解析字符串;有没有更清洁的方法?

c# - 我怎样才能得到linq中的计数?

java.lang.IndexOutOfBoundsException : Index 7, 大小:7

android - Vibrator.vibrate() 抛出 ArrayIndexOutOfBoundsException