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

Noe*_*oel 6 asp.net serialization json nullable asp.net-ajax

以下类不使用反序列化(但序列化)System.Web.Script.Serialization.JavaScriptSerializer.

public class foo {
  public KeyValuePair<string, string>? bar {get;set;}
}
Run Code Online (Sandbox Code Playgroud)

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

更改属性类型以KeyValuePair<string,string>修复问题,但我想尽可能保留Nullable类型.

JSON正是您所期望的:

{"foo": {
  "bar": {
    "Key":"Jean-Luc",
    "Value":"Picard"
  }
}}
Run Code Online (Sandbox Code Playgroud)

救命?

Joh*_*ohn 5

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

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

您将能够通过创建一个实现JavaScriptConverter 的类并注册它来解决此问题和 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>) }; }
    }
}
Run Code Online (Sandbox Code Playgroud)

或者,您可以创建一个具有两个属性 key 和 value 的简单类。