Serialize hashtable using Protocol Buffers (.NET)

2019-08-02 23:57发布

问题:

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