我目前正在做一个POC来证明Protobuf-net比原生C#序列化器更快。但是我遇到了一个错误?关于序列化响应。
这是错误
nativeResult
<?xml version="1.0"?>
<userInformation xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<age>22</age>
<education>Cavite State University</education>
<name>Ronald Estacion</name>
<address>
<city>Cavite</city>
<country>PH</country>
<street>Torjak Street</street>
<subd>Yari ka ngayon</subd>
</address>
</userInformation>
protoresult
这是我的代码。
var nativeSerializer = new XmlSerializer(typeof(UserInformation));
var nativeStream = new MemoryStream();
var protoStream = new MemoryStream();
nativeSerializer.Serialize(nativeStream, CreateDetaulUserInformation());
var nativeResult = Encoding.UTF8.GetString(nativeStream.ToArray());
Serializer.Serialize(protoStream, CreateDetaulUserInformation());
var protoResult = Encoding.UTF8.GetString(protoStream.ToArray());
这是UserInformation对象。
//[ProtoContract]
[XmlType("address")]
public class Address
{
//[ProtoMember(1)]
[XmlElement("city", Order = 1)]
public string City { get; set; }
//[ProtoMember(2)]
[XmlElement("country", Order = 2)]
public string Country { get; set; }
//[ProtoMember(3)]
[XmlElement("street", Order = 3)]
public string Street { get; set; }
//[ProtoMember(4)]
[XmlElement("subd", Order = 4)]
public string Subdivision { get; set; }
}
//[ProtoContract]
[XmlType("userInformation")]
public class UserInformation
{
//[ProtoMember(1)]
[XmlElement("age", Order = 1)]
public int Age { get; set; }
//[ProtoMember(2)]
[XmlElement("education", Order = 2)]
public string Education { get; set; }
//[ProtoMember(3)]
[XmlElement("name", Order = 3)]
public string Name { get; set; }
//[ProtoMember(4)]
[XmlElement("address", Order = 4)]
public Address Address { get; set; }
}
注意:我还尝试使用ProtoContract
作为属性,但结果相同。 Protobuf-net支持XmlType
,所以我评论了这些属性。
答案 0 :(得分:1)
这是您的错误:
var protoResult = Encoding.UTF8.GetString(protoStream.ToArray());
protobuf是二进制协议;它是不文本,并且特别不是UTF8。当输入数据不是UTF-8缓冲区时,您正在尝试解码 UTF-8缓冲区为字符串。
如果您想将原始byte[]
变为string
,那么Convert.ToBase64String
就是您的朋友。但是,如果可以避免这样做:如果可能的话,最好将其视为二进制端到端。
作为一个非常小的事情:没有必要在这里调用ToArray()
- 强制额外的数组副本。如果可能,请使用GetBuffer()
与 .Length
结合使用(底层缓冲区超大);即。
string base64 = Convert.ToBase64String(
protoStream.GetBuffer(), 0, (int)protoStream.Length);