加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

无法使用ASP.NET AJAX从JSON反序列化Nullable KeyValuePair

发布时间:2020-12-16 03:53:47 所属栏目:asp.Net 来源:网络整理
导读:以下类不使用System.Web.Script.Serialization. JavaScriptSerializer反序列化(但确实序列化). public class foo { public KeyValuePairstring,string? bar {get;set;}} 当System.Web.Script.Serialization.ObjectConverter.ConvertDictionaryToObject到达ba
以下类不使用System.Web.Script.Serialization. JavaScriptSerializer反序列化(但确实序列化).

public class foo {
  public KeyValuePair<string,string>? bar {get;set;}
}

当System.Web.Script.Serialization.ObjectConverter.ConvertDictionaryToObject到达bar属性时,反序列化的尝试导致System.NullReferenceException. (注意,这是基于堆栈跟踪的推测.)

将属性类型更改为KeyValuePair< string,string>解决了这个问题,但是如果可能的话我想保留Nullable类型.

JSON正是您所期望的:

{"foo": {
  "bar": {
    "Key":"Jean-Luc","Value":"Picard"
  }
}}

救命?

解决方法

发生这种情况的原因是,当JavaScriptSerializer尝试反序列化时,它将创建该类的新实例(在此KeyValuePair中),然后将值分配给属性.

这会导致问题,因为KeyValuePair只能将键和值分配为构造函数的一部分而不是通过属性,因此会产生空键和值.

您将能够通过创建实现JavaScriptConverter和Registering It的类来解决此问题和null问题.我已使用下面的代码来处理标准KeyValuePair但我相信您可以扩展它以处理空值.

public class DictionaryJavaScriptConverter<k,v> : JavaScriptConverter
{

    public override object Deserialize(System.Collections.Generic.IDictionary<string,object> dictionary,System.Type type,System.Web.Script.Serialization.JavaScriptSerializer serializer)
    {
        return new KeyValuePair<k,v>((k)dictionary["Key"],(v)dictionary["Value"]);
    }

    public override System.Collections.Generic.IDictionary<string,object> Serialize(object obj,System.Web.Script.Serialization.JavaScriptSerializer serializer)
    {
        throw new NotImplementedException();
    }

    public override System.Collections.Generic.IEnumerable<System.Type> SupportedTypes {
        get { return new System.Type[] { typeof(KeyValuePair<k,v>) }; }
    }
}

或者,您可以创建一个具有两个属性键和值的简单类.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读