序列化和反序列化Dictionary使用JavaScriptSerializer和自定义Jav

本文关键字:使用 JavaScriptSerializer 自定义 Jav object 反序列化 Dictionary int 序列化 | 更新日期: 2023-09-27 18:08:06

如何使用JavaScriptSerializer和自定义JavaScriptConverter将键为整数字典序列化和反序列化为JSON ?

对于那些不知道的人来说,JavaScripSerializer不能开箱操作。

请注意,我对需要在序列化之前转换字典或使用另一个序列化器的解决方案不感兴趣(如果你是,你可以看到这篇文章)。

UPDATE:为了消除任何歧义,我对键在JSON中作为字符串生成的事实没有任何问题(因此1将成为"1")。

序列化和反序列化Dictionary<int, object>使用JavaScriptSerializer和自定义Jav

/// <summary>
/// Implements JavaScript Serialization and Deserialization for instances of the Dictionary&lt;int, object&gt; type.
/// </summary>
public class IntDictionaryConverter : JavaScriptConverter
{
    /// <summary>
    /// Converts the provided dictionary into a Dictionary&lt;int, object&gt; object.
    /// </summary>
    /// <param name="dictionary">An IDictionary instance of property data stored as name/value pairs.</param>
    /// <param name="type">The type of the resulting object.</param>
    /// <param name="serializer">The JavaScriptSerializer instance.</param>
    /// <returns>The deserialized object.</returns>
    public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
    {
        // Validate arguments
        if (dictionary == null) throw new ArgumentNullException("dictionary");
        if (serializer == null) throw new ArgumentNullException("serializer");
        Dictionary<int, object> deserializedDictionary = new Dictionary<int, object>();
        foreach (KeyValuePair<string, object> entry in dictionary)
        {
            int intKey = 0;
            if (!int.TryParse(entry.Key, out intKey))
                throw new InvalidOperationException("Cannot deserialize the dictionary because of invalid number string");
            deserializedDictionary.Add(intKey, entry.Value);
        }
        return deserializedDictionary;
    }
    /// <summary>
    /// Builds a dictionary of name/value pairs.
    /// </summary>
    /// <param name="obj">The object to serialize.</param>
    /// <param name="serializer">The object that is responsible for the serialization.</param>
    /// <returns>An object that contains key/value pairs that represent the object’s data.</returns>
    public override IDictionary<string, object> Serialize(object obj, JavaScriptSerializer serializer)
    {
        // Validate arguments
        if (obj == null) throw new ArgumentNullException("obj");
        if (serializer == null) throw new ArgumentNullException("serializer");
        // Get the dictionary to convert
        Dictionary<int, object> dictionary = (Dictionary<int, object>)obj;
        // Build the converted dictionary
        Dictionary<string, object> convertedDictionary = new Dictionary<string, object>();
        foreach (KeyValuePair<int, object> entry in dictionary)
            convertedDictionary.Add(entry.Key.ToString(), entry.Value);
        return convertedDictionary;
    }
    /// <summary>
    /// Gets a collection of the supported types.
    /// </summary>
    public override System.Collections.Generic.IEnumerable<Type> SupportedTypes
    {
        get
        {
            return new Type[]
            {
                typeof(Dictionary<int, object>)
            };
        }
    }
}