Serialize hashtable using Protocol Buffers (.NET)

僤鯓⒐⒋嵵緔 提交于 2019-12-11 08:22:27

问题


I am trying to serialize/deserialize my custom class which contains hashtable property using protobuf-net v2.

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

When I call Serializer.Serialize(...) exception appears: No serializer defined for type: System.Collections.Hashtable

I try to modify:

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

But I have another exception: Type is not expected, and no contract can be inferred: System.Collections.DictionaryEntry

Maybe someone know a way how I can serialize hashtable?


回答1:


Thanks to all who helped me. Here is my solution. I know that this is not best way, but maybe for someone it acceptable.

    [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());
        }
    }


来源:https://stackoverflow.com/questions/10615896/serialize-hashtable-using-protocol-buffers-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!