【问题标题】:Serialize and deserialize Dictionary<int, object> using JavaScriptSerializer and a custom JavaScriptConverter使用 JavaScriptSerializer 和自定义 JavaScriptConverter 序列化和反序列化 Dictionary<int, object>
【发布时间】:2015-11-07 11:43:09
【问题描述】:

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

对于那些不知道的人,JavaScripSerializer 不能开箱即用。

请注意,我对需要在序列化之前转换字典或使用其他序列化程序的解决方案不感兴趣(如果您愿意,您可能会看到 this post)。

更新:为了消除歧义,我对密钥生成为 JSON 中的字符串这一事实没有任何问题(因此 1 将变为“1”)。

【问题讨论】:

  • 因此,您希望 JSON 名称不是 string 值,而是 int。是否完全符合 JSON 对象名/值对格式?
  • @AndrewOrlov 是的,这就是我想要的。我看不出它是如何违反 JSON 格式的(您可以使用任何字符串键;“1”将是有效键)。对我来说最重要的是 javaScriptSerializer.Deserialize(javaScriptSerializer.Serialize(dictionary)) 工作顺利。
  • 为什么不赞成,请添加评论,以便我们改进问题。如果您没有答案,则无需投票。
  • JavaScriptSerializer.Deserialize 方法按照 JSON 格式的要求工作。有了这个要求,你的键类型应该只有string,并且方法会在另一种情况下抛出特殊的参数异常——“字典的序列化/反序列化不支持类型,键必须是字符串或对象”。所以,是的,这是一种违规行为。以及为什么您不想将 JSON 反序列化为 IDictionary&lt;string, object&gt;,然后将 string 密钥转换为 int
  • 那么请随意打开这篇文章stackoverflow.com/questions/5597349/… 并对所有问题和答案投反对票。我正在尝试修复 asmx 服务,并且碰巧在 webmethods 中使用的某些类包含这种类型。我不希望 asmx 规定后端类的实现。这会一次又一次地崩溃。

标签: c# json dictionary serialization javascriptserializer


【解决方案1】:
/// <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>)
            };
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    • 2019-08-10
    • 1970-01-01
    • 2012-09-15
    相关资源
    最近更新 更多