![](/img/trans.png)
[英]Constructor of a XmlSerializer serializing a List<T> throws an InvalidOperationException when used with XmlAttributeOverrides
[英]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是protobuf的替代引擎,它使用標准的.NET慣用語,因此可能效果很好 。 您需要更改protobuf代碼以使用protobuf-net庫,但是它應該兼容。
處理.proto的工具有多種方式,最簡單的方法是通過https://protogen.marcgravell.com
設法弄清楚了。 SendMessage
消息包含一個無法序列化的bytes
字段。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.