Search code examples
c#protocol-buffersxmlserializer

XMLSerializer InvalidOperationException when serializing protobuf


I have the following protobuf messages defined:

message ClientMessage{
    oneof data{
        CheckAlive alive = 1;
        Login login = 2;
        SendMessage sendMessage = 3;
        Logout logout = 4;
    }
}

When I try to use XmlSerializer to serialize ClientMessage with i get the following exception:

System.InvalidOperationException: 'To be XML serializable, types which inherit from IEnumerable must have an implementation of Add(System.Object) at all levels of their inheritance hierarchy. Google.Protobuf.ByteString does not implement Add(System.Object).'

Code used to serialize the object:

using (var stream = MemoryUtils.MemoryStreamManager.GetStream())
using (var xml = new XmlTextWriter(stream, Encoding.UTF8))
    {
        var xs = new XmlSerializer(typeof(T));
        xs.Serialize(xml, item);

        using (var reader = new StreamReader(stream, Encoding.UTF8, true))
        {
             stream.Seek(0, SeekOrigin.Begin);
             return reader.ReadToEnd();
        }
    }

Solution

  • Managed to figure it out. The SendMessage message contained a bytes field which could not be serialized.