Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 序列化和反序列化字典<;int,object>;使用JavaScriptSerializer和自定义JavaScriptConverter_C#_Json_Dictionary_Serialization_Javascriptserializer - Fatal编程技术网

C# 序列化和反序列化字典<;int,object>;使用JavaScriptSerializer和自定义JavaScriptConverter

C# 序列化和反序列化字典<;int,object>;使用JavaScriptSerializer和自定义JavaScriptConverter,c#,json,dictionary,serialization,javascriptserializer,C#,Json,Dictionary,Serialization,Javascriptserializer,如何将键为整数的字典序列化和反序列化为JSON,并使用 对于那些不知道的人来说,JavaScripSerializer无法做到开箱即用 请注意,我对需要在序列化之前转换字典或使用其他序列化程序的解决方案不感兴趣(如果您感兴趣,您可能会看到) 更新:为了消除任何歧义,我对键在JSON中生成为字符串这一事实没有任何问题(因此1将变为“1”) // ///为Dictionaryint对象类型的实例实现JavaScript序列化和反序列化。 /// 公共类IntDictionaryConverter:

如何将键为整数的字典序列化和反序列化为JSON,并使用

对于那些不知道的人来说,JavaScripSerializer无法做到开箱即用

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

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

//
///为Dictionaryint对象类型的实例实现JavaScript序列化和反序列化。
/// 
公共类IntDictionaryConverter:JavaScriptConverter
{
/// 
///将提供的字典转换为DictionaryNT对象。
/// 
///作为名称/值对存储的属性数据的IDictionary实例。
///结果对象的类型。
///JavaScriptSerializer实例。
///反序列化的对象。
公共重写对象反序列化(IDictionary dictionary、类型、JavaScriptSerializer序列化程序)
{
//验证参数
如果(dictionary==null)抛出新的ArgumentNullException(“dictionary”);
如果(serializer==null)抛出新的ArgumentNullException(“serializer”);
Dictionary deserializedDictionary=新字典();
foreach(字典中的KeyValuePair条目)
{
int intKey=0;
如果(!int.TryParse(entry.Key,out intKey))
抛出新的InvalidOperationException(“由于无效的数字字符串,无法反序列化字典”);
反序列化的dictionary.Add(intKey,entry.Value);
}
返回反序列化字典;
}
/// 
///构建名称/值对的字典。
/// 
///要序列化的对象。
///负责序列化的对象。
///包含表示对象数据的键/值对的对象。
公共重写IDictionary序列化(对象obj、JavaScriptSerializer序列化程序)
{
//验证参数
如果(obj==null)抛出新的ArgumentNullException(“obj”);
如果(serializer==null)抛出新的ArgumentNullException(“serializer”);
//让字典转换
Dictionary Dictionary=(Dictionary)obj;
//构建转换后的词典
Dictionary convertedDictionary=新字典();
foreach(字典中的KeyValuePair条目)
convertedDictionary.Add(entry.Key.ToString(),entry.Value);
返回转换文档;
}
/// 
///获取受支持类型的集合。
/// 
公共覆盖System.Collections.Generic.IEnumerable SupportedTypes
{
得到
{
返回新类型[]
{
类型(字典)
};
}
}
}

因此,您希望JSON名称不是
字符串
值,而是
int
。它与JSON对象名/值对格式完全一致吗?@AndrewOrlov是的,这就是我想要的。我看不出它是如何违反JSON格式的(您可以使用任何字符串键;“1”将是有效键)。对我来说最重要的是javaScriptSerializer.Deserialize(javaScriptSerializer.Serialize(dictionary))工作得很顺利。为什么会有反对票,请添加一条评论,这样我们就可以完善这个问题了。如果没有答案,则无需向下投票。
JavaScriptSerializer.Deserialize
方法根据JSON格式的要求工作。根据此要求,您的键类型应仅为
string
,并且对于另一种情况,该方法会引发特殊的参数异常——“字典的序列化/反序列化不支持类型,键必须是字符串或对象”。所以,是的,这是一种违反。为什么你不想将JSON反序列化为
IDictionary
,然后将
string
键转换为
int
?那么请随意打开本文并对所有问题和答案进行向下投票。我正在尝试修复一个asmx服务,碰巧webmethods中使用的某些类包含这种类型。我不希望asmx命令后端类的实现。这会一次又一次地破裂。
/// <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>)
            };
        }
    }
}