我是序列化的新手,我遇到了一个问题。我有一个REST服务,它返回一个IDDescriptionPair对象数组。在使用服务时,我使用“将XML粘贴为类型”VS加载项来创建对象。我只修改此对象以添加DataContract属性,以便我的命名空间在每一端都匹配。这是对象:
Imports System.Runtime.Serialization
<DataContract([Name]:="IDDescriptionPair", [Namespace]:="http://schemas.datacontract.org/2004/07/Blizzard.ClassLibrary")>
<System.CodeDom.Compiler.GeneratedCodeAttribute("System.Xml", "4.0.30319.225"), _
System.Diagnostics.DebuggerStepThroughAttribute(), _
System.Xml.Serialization.XmlTypeAttribute([Namespace]:="http://schemas.datacontract.org/2004/07/Blizzard.ClassLibrary"), _
System.Xml.Serialization.XmlRootAttribute ([Namespace]:="http://schemas.datacontract.org/2004/07/Blizzard.ClassLibrary", IsNullable:=True)> _
Partial Public Class IDDescriptionPair
Private descriptionField As String
Private idField As Integer
Private idFieldSpecified As Boolean
'''<remarks/>
<System.Xml.Serialization.XmlElementAttribute(IsNullable:=True)> _
Public Property Description() As String
Get
Return Me.descriptionField
End Get
Set(value As String)
Me.descriptionField = value
End Set
End Property
'''<remarks/>
Public Property ID() As Integer
Get
Return Me.idField
End Get
Set(value As Integer)
Me.idField = value
End Set
End Property
'''<remarks/>
<System.Xml.Serialization.XmlIgnoreAttribute()> _
Public Property IDSpecified() As Boolean
Get
Return Me.idFieldSpecified
End Get
Set(value As Boolean)
Me.idFieldSpecified = value
End Set
End Property
End Class
我可以调用该服务并反序列化该对象,它似乎工作正常。我得到了正确数量的IDDescriptionPair对象的列表。问题是它们都是空白的 - 没有填充任何属性。
这是我使用服务的代码:
Dim client As New HttpClient()
Dim endpoint As New Uri("http://bmpscnt410a/services/v1/personservices/offices/5/principals")
Using response As HttpResponseMessage = client.Get(endpoint)
response.EnsureStatusIsSuccessful()
Dim idp As List(Of IDDescriptionPair)
Try
idp = response.Content.ReadAsDataContract(Of List(Of IDDescriptionPair))()
Catch ex As Exception
End Try
End Using
我已经尝试过直接使用DataContractSerializer,但我得到了相同的结果(我想这是预期的)。任何想法都将不胜感激。
答案 0 :(得分:1)
您使用的类型是XmlSerializer类型(使用System.Xml.Serialization
命名空间中的属性进行注释,例如<XmlType()>
,<XmlRoot()>
等等。为此,您需要使用XmlSerializer
对其进行反序列化。如果您包含(导入)命名空间System.Xml.Serialization
,您应该获得扩展方法ReadAsXmlSerializable
,这是您应该用来反序列化响应的方法。