Unable to deserialize Nullable KeyValuePair from JSON using ASP.NET AJAX

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

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

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

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

JSON is exactly what you expect:

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

reference

+6
json serialization nullable asp.net-ajax
source share
2 answers

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

This causes a problem, since KeyValuePair can only have a key and values ​​assigned as part of the constructor, and not through properties, so we get an empty key and value.

You can solve this and the null problem by creating a class that implements JavaScriptConverter and registering it . I used the code below to handle the standard KeyValuePair, but I'm sure you can extend it to handle zeros.

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

Alternatively, you can create a simple class with two keys and a property value.

+4
source share

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

I have successfully Json serialized and deserialized a pair of KeyValue keys using it.

0
source share

All Articles