用列表嵌套WCF数据契约



我已经设置了我的WCF服务如下:

<ServiceContract()>
Public Interface MyInterface
 <OperationContract()>
 Function Search(ByVal parm1As String, ByVal parm2 As String, ByVal parm3 As String) As MyResponse
End Interface
<DataContract()>
Public Class MyResponse
<DataMember()>
Public Property SearchResult() As SearchRes
<DataMember()>
Public Property RecordInfo() As List(Of RecordInf)
<DataContract()>
Public Class SearchRes
    <DataMember()>
    Public Property Prop1() As String
    <DataMember()>
    Public Property Prop2() As Integer
    <DataMember()>
    Public Property Prop3() As String
End Class
<DataContract()>
Public Class RecordInf
    <DataMember()>
    Public Property Prop4() As String
    <DataMember()>
    Public Property Prop5() As String
    <DataMember()>
    Public Property Prop6() As List(Of MyList)
    <DataMember()>
    Public Property Prop7() As String
    <DataMember()>
    Public Property Prop8() As String
    <DataMember()>
    Public Property Prop9() As String
    <DataMember()>
    Public Property Prop10() As String
End Class
<DataContract()>
Public Class Contr
    <DataMember()>
    Public Property Prop11() As String
End Class

唯一的问题是这样的响应返回:

<s:Header />
  <s:Body>
    <SearchResponse xmlns="http://tempuri.org/">
      <SearchResult xmlns:a="http://schemas.datacontract.org/2004/07/MyService" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
        <a:RecordInfo>
          <a:MyResponse.RecordInf>
            <a:Prop10>Yes</a:Prop10>
            <a:Prop6>
              <a:MyResponse.MyList>
                <a:Prop11>Blah</a:Prop11>
              </a:MyResponse.MyList>
            </a:Prop6>
            <a:Prop5>9780800720957</a:Prop5>
            <a:Prop8>pb</a:Prop8>
            <a:Prop9>9.45</a:Prop9>
            <a:Prop7>Blah</a:Prop7>
            <a:Prop4>Blah</a:Prop4>
          </a:MyResponse.RecordInf>
        </a:RecordInfo>
        <a:SearchResult>
          <a:Prop3 i:nil="true" />
          <a:Prop2>1</a:Prop2>
          <a:Prop1>1</a:Prop1>
        </a:SearchResult>
      </SearchResult>
    </SearchResponse>
  </s:Body>

从上面可以看到,在a:RecordInfo之后,它放置了类- a:MyResponse。我不想要的录音。如何正确设置,使XML不嵌套在那里的类名?

您已经将RecordInfo声明为RecordInf对象的列表,因此列表中可能有几个对象,并且WCF需要打开和关闭标记来区分一个记录和另一个记录。否则,所有记录的所有属性都将在同一个标签下。

如果您的RecordInfo总是只包含一条记录-将列表替换为单个RecordInf结构

这是DataContractSerializer对集合类型(List是)的属性的默认(和正常)行为。根据文档(MSDN):

自定义列表集合中的重复元素名称

List集合包含重复的项。通常,每个重复条目表示为根据数据命名的元素集合中包含的类型的契约名称。

在CustomerList示例中,集合包含字符串。的字符串原语类型的数据契约名称为"string",因此重复元素为&lt;string&gt;

您也可以更改此行为。不过,您必须稍微更改一下datcontract。您必须引入您自己的列表类型(Inherits List(Of T)),然后您可以用CollectionDataContract属性注释这个新的列表类型,其中您可以设置ItemName来控制列表如何被序列化。

下面的列表类定义将为您解决这个问题。只需将MyResponse类中的RecordInfo更改为RecordInfList类型。

<CollectionDataContract(ItemName:="RecordInf")>
Class RecordInfList
    Inherits List(Of RecordInf)
End Class

请注意,以下注释来自文档(MSDN):

自定义集合类型

属性来自定义集合类型CollectionDataContractAttribute属性,它有几种用途。

注意自定义集合类型会损害集合互换性,所以一般建议避免使用尽可能地使用此属性。了解更多相关信息问题,请参阅本文后面的"高级收集规则"部分话题。

最新更新