如何设置数组列表序列化和避免类型是不期望的
本文关键字:类型 期望 序列化 何设置 设置 列表 数组 | 更新日期: 2023-09-27 18:14:44
我需要将数组列表传递给SOAP服务:
var arrayList = new ArrayList
{
"simple",
"4",
"two",
new StringKeyValuePair {Key = "name", Value = "product name"}
};
[Serializable]
public struct StringKeyValuePair
{
public string Key { get; set; }
public string Value { get; set; }
}
调用看起来像:
client.call(sessionId, "product.create", arrayList);
WSDL看起来像:
<message name="call">
<part name="sessionId" type="xsd:string"/>
<part name="resourcePath" type="xsd:string"/>
<part name="args" type="xsd:anyType"/>
</message>
问题是,soap客户端不能序列化它,因为StringKeyValuePair不是期望的类型。我不能将它作为属性包装到类中,因为这会导致soap服务无法理解(无法更改soap服务)的额外xml。
您可以将其序列化传递。
var arrayList = new ArrayList
{
"simple",
"4",
"two",
"<KeyValuePair><Pair Key='"name'">product name</Pair></KeyValuePair>"
};
是否没有办法传入类型安全的对象,如列表或数组?
您必须使用XmlInclude
属性
public class MyService: WebService {
[WebMethod()]
[XmlInclude(typeof(StringKeyValuePair))]
public ArrayList YourMethod() {
//...
}
}
我发现了一个问题和一个解决方案。问题是,只要args参数类型是any,客户端就不知道期望的类型是什么。因此,解决方案是将KnowType添加到操作中(在下面的示例中,它被添加到所有操作中):
foreach (var operation in client.Endpoint.Contract.Operations)
{
operation.KnownTypes.Add(typeof(StringKeyValuePair));
}