AqlaSolutions / AqlaSerializer

Binary serializer with full .NET support!
http://www.aqla.net
Other
17 stars 3 forks source link

Can I serialize a tuple? #27

Closed SpeedysWorkingArray closed 2 years ago

SpeedysWorkingArray commented 2 years ago

Hello together, I had tried to serialize a simple tuple in a small test, but did not get the wanted result when deserializing. Is it possible to serialize a tuple?

image

namespace SerializerTest
{
    public class SerializerTest
    {
        [Fact]
        public void Can_serialize_object_with_tuple()
        {
            Tuple<int, string> tuple = new Tuple<int, string>(1, "abc");
            ClassWithTupleMember objectWithTuple = new ClassWithTupleMember() { Tuple = tuple };
            byte[] serializedObject = Serialize<ClassWithTupleMember>(objectWithTuple);
            var deserializedObject = Deserialize<ClassWithTupleMember>(serializedObject);

            deserializedObject.Tuple.ShouldBe(tuple);
        }

        public static byte[] Serialize<T>(T objectToSerialize) where T : class
        {
            if (objectToSerialize is null) return null;

            var memoryStream = new MemoryStream();
            global::AqlaSerializer.Serializer.Serialize<T>(memoryStream, objectToSerialize);
            return memoryStream.ToArray();
        }

        public static T Deserialize<T>(byte[] serializedMessage) where T : class
        {
            if (serializedMessage is null) return default;

            try
            {
                var memoryStream = new MemoryStream(serializedMessage) { Position = 0 };
                return global::AqlaSerializer.Serializer.Deserialize<T>(memoryStream);
            }
            catch (Exception)
            {
                return (T)Activator.CreateInstance(typeof(T));
            }
        }
    }

    [SerializableType()]
    public class ClassWithTupleMember
    {
        public Tuple<int, string> Tuple;
    }
}
AqlaSolutions commented 2 years ago

You've forgotten [SerializableMember(1)]

SpeedysWorkingArray commented 2 years ago

Runs, thank you very much! 👍😃