序列化 protobuf 时出现 XMLSerializer InvalidOperationException

XMLSerializer InvalidOperationException when serializing protobuf

我定义了以下 protobuf 消息:

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

当我尝试使用 XmlSerializer 序列化 ClientMessage 时出现以下异常:

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).'

用于序列化对象的代码:

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

一般来说,生成的 POCO 只能与它们设计的引擎一起使用。然而! Protobuf-net 是使用标准 .NET 习惯用法的 protobuf 的替代引擎,因此 可能工作得很好 。您需要更改 protobuf 代码才能使用 protobuf-net 库,但它应该是兼容的。

处理 .proto 的工具有多种方式,最简单的方法是 https://protogen.marcgravell.com

设法弄明白了。 SendMessage 消息包含无法序列化的 bytes 字段。