开发者

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

The following class does not deserialize (but does serialize) using System.Web.Script.Serialization.JavaScriptSeriali开发者_开发知识库zer.

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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜