I’m adding this here as a reminder to myself. If you want to convert a dictionary in simple JSON format to a dictionary in .NET 4.0, you can’t use the DataContractJsonSerializerSettings that is available in .NET 4.5, so if you don’t want to use a 3rd party source (like JSON.NET), you need to be able to serialize/deserialize it yourself. Fortunately, this is fairly simple for a dictionary as follows:

using System;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace x
{
    [Serializable]
    public class JSONDictionary<T> : Dictionary<string, T>, ISerializable
    {
        protected JSONDictionary(SerializationInfo info, 
                                 StreamingContext context)
        {
            foreach (SerializationEntry value in info)
                Add(value.Name, (T)info.GetValue(value.Name, typeof(T)));
        }

        public override void GetObjectData(SerializationInfo info, 
                                           StreamingContext context)
        {
            foreach (KeyValuePair<string, T> value in this)
                info.AddValue(value.Key, value.Value);
        }
    }
}

Then just use this in place of the dictionary in your serializable object.

[DataContract()]
public class Response
{
    [DataMember(Name = "my_dictionary", IsRequired = true)]
    public JSONDictionary<double> MyDictionary { get; set; }
}

And you’re all set. (Note that I haven’t dealt with dictionary keys of types other than string.)

Advertisements