【问题标题】:Serialize hashtable using Protocol Buffers (.NET)使用协议缓冲区 (.NET) 序列化哈希表
【发布时间】:2012-05-16 09:40:13
【问题描述】:

我正在尝试使用 protobuf-net v2 序列化/反序列化包含哈希表属性的自定义类。

    [ProtoContract]
    public class MyClass
    {
        [ProtoMember(1)]
        public Hashtable MyHashTable { get; set; }
   }

当我调用 Serializer.Serialize(...) 时出现异常: 没有为类型定义序列化程序:System.Collections.Hashtable

我尝试修改:

    [ProtoContract]
    public class MyClass
    {
        [ProtoMember(1, DynamicType = true)]
        public Hashtable MyHashTable { get; set; }
   }

但我还有一个例外: 类型不是预期的,也无法推断出合约:System.Collections.DictionaryEntry

也许有人知道我可以如何序列化哈希表?

【问题讨论】:

  • 是要序列化存储在哈希表中的对象还是哈希表本身?
  • 存储哈希表并在反序列化后使用它会很好,但如果有办法只存储哈希表中的对象 - 没关系。
  • protobuf-net 目前不直接支持这种方案,我不确定它是否是我急于支持的方案。在基于契约的序列化程序中,意图是您提前知道数据的形状。例如,Dictionary<string, SomeType> 会工作很好,因为很清楚这意味着什么以及数据将包含什么。
  • 你可以试试这个:techrepublic.com/blog/howdoi/…
  • eyossi ,我需要使用 protobuf 因为性能对我来说非常重要。 @Marc Gravell♦ 谢谢,我知道这个解决方案,但我希望我能找到更好的解决方案。

标签: .net protocol-buffers protobuf-net


【解决方案1】:

感谢所有帮助过我的人。这是我的解决方案。我知道这不是最好的方法,但也许有人可以接受。

    [ProtoContract]
    public class HashtableTestClass
    {
        private string inputParametersBase64 = string.Empty;
        private Hashtable myHashTable;

        public Hashtable MyHashtable
        {
            get { return myHashTable; }
            set { myHashTable = value; }
        }

        [ProtoMember(1)]
        public string InputParametersBase64
        {
            get
            {
                if (myHashTable == null)
                    return string.Empty;

                return HashtableToBase64(myHashTable);
            }
            set
            {
                inputParametersBase64 = value;
                if (!string.IsNullOrEmpty(inputParametersBase64))
                {
                    try
                    {
                        myHashTable = Base64ToHashtable(inputParametersBase64);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e);
                    }
                }
            }
        }

        public static Hashtable Base64ToHashtable(string s)
        {
            MemoryStream stream = new MemoryStream(Convert.FromBase64String(s), false);
            IFormatter formatter = new BinaryFormatter();

            return (Hashtable)formatter.Deserialize(stream);
        }

        public static string HashtableToBase64(Hashtable hashtable)
        {
            IFormatter formatter = new BinaryFormatter();
            MemoryStream stream = new MemoryStream();
            formatter.Serialize(stream, hashtable);
            stream.Close();
            return Convert.ToBase64String(stream.ToArray());
        }
    }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-05-15
    • 2011-05-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    相关资源
    最近更新 更多