Can't Deserialize a Nullable KeyValuePair from JSON with ASP.NET AJAX

偶尔善良 提交于 2019-12-07 04:02:56

问题


The following class does not deserialize (but does serialize) using System.Web.Script.Serialization.JavaScriptSerializer.

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

The attempt to deserialize results in a System.NullReferenceException when System.Web.Script.Serialization.ObjectConverter.ConvertDictionaryToObject reaches the bar property. (Note, that is a surmise based on the stack trace.)

Changing the property type to KeyValuePair<string,string> fixes the problem, but I'd like to keep the Nullable type if at all possible.

The JSON is exactly what you would expect:

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

Help?


回答1:


The reason this happens is that when the JavaScriptSerializer tries to deserialize it will create a new instance of the class (in this the KeyValuePair) and then assign the values to properties.

This causes an issue as the KeyValuePair can only have the key and values assigned as part of the constructor and not via properties so results in an empty key and value.

You will be able to resolve this and the null issue by creating a class that implements JavaScriptConverter and Registering It. I have used the code below to handle a standard KeyValuePair but I am sure you can extend it to handle nulls.

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>) }; }
    }
}

Alternately you can create a simple class that has two properties key and value.




回答2:


You can have a look at this wrapper: http://www.codeproject.com/KB/aspnet/Univar.aspx

I've successfully Json serialized and deserialized the nullable KeyValue pair using it.



来源:https://stackoverflow.com/questions/1785283/cant-deserialize-a-nullable-keyvaluepair-from-json-with-asp-net-ajax

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!