1

我正在测试通过 WCF 服务发送一个复杂的消息对象并得到各种序列化错误。为了简化事情,我试图将其缩减为仅测试DataContractSerializer,为此我根据此处的代码编写了以下测试:

Dim message As TLAMessage = MockFactory.GetMessage
Dim dcs As DataContractSerializer = New DataContractSerializer(GetType(TLAMessage))
Dim xml As String = String.Empty

Using stream As New StringWriter(), writer As XmlWriter = XmlWriter.Create(stream)
    dcs.WriteObject(writer, message)
    xml = stream.ToString
End Using

Debug.Print(xml)

Dim newMessage As TLAMessage
Dim sr As New StringReader(xml)
Dim reader As XmlReader = XmlReader.Create(sr)
dcs = New DataContractSerializer(GetType(TLAMessage))
newMessage = CType(dcs.ReadObject(reader, True), TLAMessage) 'Error here
reader.Close()
sr.Close()

Assert.IsTrue(newMessage IsNot Nothing)

但是,这在调用以下命令时本身会出现异常错误ReadObjectUnexpected end of file while parsing Name has occurred. Line 1, position 6144

这似乎是一个缓冲错误,但我看不到如何在字符串上“ReadToEnd”。我尝试过使用 a MemoryStream:Dim ms As New MemoryStream(Encoding.UTF8.GetBytes(xml))和 aStreamWriter但它们中的每一个都有自己的错误,或者与采用各种不同重载的ReadObject方法不兼容。DataContractSerializer

请注意,从 MSDN 页面调整代码可以正常工作,但需要序列化到文件,但是我想序列化到字符串或从字符串序列化,但我认为我遗漏了一些重要的东西。

我在上面的代码中遗漏了一些明显的东西吗?

4

1 回答 1

4

您的数据XmlWriter不会立即填充到基础StringWriter. 所以你应该在写完之后刷新作者:

dcs.WriteObject(writer, message)
writer.Flush()
xml = stream.ToString()
于 2013-07-01T08:45:55.047 回答