2013-07-01 27 views
1

我正在测试通过WCF服务发送复杂的消息对象并获取各种序列化错误。为了简化事情我想剪下来,只是测试DataContractSerializer,对此我已经基于代码here写了下面的测试:使用字符串测试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) 

然而,这得到一个不同寻常的错误本身ReadObject的呼叫:Unexpected end of file while parsing Name has occurred. Line 1, position 6144

它似乎是一个缓冲错误,但我看不到如何在字符串上'ReadToEnd'。我试过使用MemoryStreamDim ms As New MemoryStream(Encoding.UTF8.GetBytes(xml))StreamWriter,但其中每一个都带有自己的错误,或者与DataContractSerializerReadObject方法不兼容,该方法会采用各种不同的重载。

请注意,适应从MSDN页面的代码工作正常,但需要序列化到一个文件,但我想序列化和从一个字符串,但我认为我错过了一些重要的东西。

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

回答

4

您的XmlWriter的数据没有立即填充到相关的StringWriter。所以你应该在写完之后冲洗笔者:

dcs.WriteObject(writer, message) 
writer.Flush() 
xml = stream.ToString() 
+0

所以很明显,我一直在错误的地方看。谢谢 –

+0

不客气。 –