Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.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?

like image 590
Noel Avatar asked Nov 23 '09 19:11

Noel


1 Answers

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.

like image 160
John Avatar answered Oct 14 '22 02:10

John