Serialization and deserialization with polymorphism and protobuffet

I am trying to use protobuf-net to serialize objects. I'm not sure if what I'm trying to do with inheritance is supported, but I thought I'd check and see if it is, or if I'm just doing something wrong.

Essentially I am trying to serialize some child class and then deserialize it, but I only do it with a reference to the base class. To demonstrate:

using UnityEngine;
using System.Collections;
using ProtoBuf;

public class main : MonoBehaviour
{
    // If I don't put "SkipConstructor = true" I get
    // ProtoException: No parameterless constructor found for Parent
    // Ideally, I wouldn't have to put "SkipConstructor = true" but I can if necessary
    [ProtoContract(SkipConstructor = true)]
    [ProtoInclude(1, typeof(Child))]
    abstract class Parent
    {
        [ProtoMember(2)]
        public float FloatValue
        {
            get;
            set;
        }

        public virtual void Print()
        {
            UnityEngine.Debug.Log("Parent: " + FloatValue);
        }
    }

    [ProtoContract]
    class Child : Parent
    {
        public Child()
        {
            FloatValue = 2.5f;
            IntValue   = 13;
        }

        [ProtoMember(3)]
        public int IntValue
        {
            get;
            set;
        }

        public override void Print()
        {
            UnityEngine.Debug.Log("Child: " + FloatValue + ", " + IntValue);
        }
    }

    void Start()
    {
        Child child = new Child();
        child.FloatValue = 3.14f;
        child.IntValue   = 42;

        System.IO.MemoryStream ms = new System.IO.MemoryStream();

        // I don't *have* to do this, I can, if needed, just use child directly.
        // But it would be cool if I could do it from an abstract reference
        Parent abstractReference = child; 

        ProtoBuf.Serializer.Serialize(ms, abstractReference);

        ProtoBuf.Serializer.Deserialize<Parent>(ms).Print();
    }
}

      

Output:

Parent: 0

I would like it to output:

Child: 3.14 42

Is it possible? And if so, what am I doing wrong? I've read various questions on SO about inheritance and protobuf-net and they are all slightly different from this example (as far as I understood them).

+3


source to share


1 answer


You will beat yourself. The code is fine, except for one thing - you forgot to rewind the stream:

ProtoBuf.Serializer.Serialize(ms, abstractReference);
ms.Position = 0; // <========= add this
ProtoBuf.Serializer.Deserialize<Parent>(ms).Print();

      



Anyway, was Deserialize

reading 0 bytes (because it was at the end), thus trying to create a parent type. An empty stream works fine in terms of the protobuf spec - it just means an object with no interesting meanings.

+9


source







All Articles