【问题标题】:REST-ful WCF service: Deserializing C# List of Strings not working properlyREST-ful WCF 服务:反序列化 C# 字符串列表无法正常工作
【发布时间】:2011-04-03 05:37:40
【问题描述】:

我有一个返回 XML 响应的 REST-ful WCF 服务。它由正确序列化和反序列化的对象组成,一个例外是节点上的 List 属性未正确反序列化。 XML 看起来像:

<ShippingGroups>
<ShippingGroup>
  <ShippingGroupId>
  b0b4d8a4-ff1f-4f02-a47c-263ef8ac861b</ShippingGroupId>
  <ShippingAddressId>
  63c0b52c-b784-4c27-a3e8-8adafba36add</ShippingAddressId>
  <LineItemIds xmlns:a="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
    <a:string>ccc0f986-52d5-453e-adca-8ff4513c1d84</a:string>
  </LineItemIds>
</ShippingGroup>

出现问题是因为我的 C# 类反序列化此 XML 需要一个 List LineItemIds。我可以通过手动删除该命名空间并删除 .

有没有其他方法可以解决这个问题,它看起来像:

<ShippingGroups>
<ShippingGroup>
  <ShippingGroupId>
  b0b4d8a4-ff1f-4f02-a47c-263ef8ac861b</ShippingGroupId>
  <ShippingAddressId>
  63c0b52c-b784-4c27-a3e8-8adafba36add</ShippingAddressId>
  <LineItemIds>
    <string>ccc0f986-52d5-453e-adca-8ff4513c1d84</string>
  </LineItemIds>
</ShippingGroup>

【问题讨论】:

  • 如何反序列化消息。该命名空间由数据协定序列化程序添加。
  • 如果您还可以展示您的 DataContract 是如何定义的,那可能会有所帮助。

标签: xml wcf rest serialization


【解决方案1】:

我想我有一个答案给你。在没有看到您的DataContracts 的情况下,我有点猜测您正在使用什么以及您的数据是如何构建的。但是这里...

我为此使用 VS2010、C#、WCF REST 和 .NET 4。

默认情况下,您的集合或数组使用默认命名空间,以便在序列化时保持互操作性。因此,您的序列化按设计运行。

如果您创建自定义集合并在其上使用CollectionDataContract 属性,则可以解决此问题。然后,您可以更好地控制它的序列化方式,包括它的命名空间。这是来自 MSDN 的 detailed explanation

所以我创建了一个自定义集合并使用 CollectionDataContract 命名空间:

[CollectionDataContract(Namespace="")]
public class StringItem2 : Collection<string>
{
}

没有属性,因为这个集合只包含字符串。

然后我的DataContract 包含我的自定义字符串集合:

[DataContract(Namespace="", IsReference=false)]
public class SampleItem
{
    [DataMember]
    public int Id { get; set; }
    [DataMember]
    public string StringValue { get; set; }
    [DataMember]
    public StringItem2 StringItems2 { get; set; }
}

现在我已经完成了,我有了简单的 WCF RESTful 服务 (GET):

[ServiceContract]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]
public class Service1
{

    [WebGet(UriTemplate = "{id}")]
    public SampleItem Get(string id)
    {
        SampleItem si = new SampleItem()
        {
            Id = 10,
            StringValue = "foo",
            StringItems2 = new StringItem2() { "Hola", "como", "esta", "usted" }
        };
        return si;
    }

}

当我请求此服务 (http://localhost:xxxx/Service1/10) 时,我收到以下 XML 作为响应:

<SampleItem xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
 <Id>10</Id> 
 <StringItems2>
  <string>Hola</string> 
  <string>como</string> 
  <string>esta</string> 
  <string>usted</string> 
 </StringItems2>
 <StringValue>foo</StringValue> 
</SampleItem>

希望这会有所帮助。请让我知道我是否遗漏了其他详细信息,或者问题是否还有其他问题。我会相应地更新我的答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-04
    • 1970-01-01
    • 2021-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多