c# WebService返回结构复杂的ArrayList 的转化问题【原】

先来看看我的Webservice方法:

 1     [WebMethod]
2 public ArrayList GetOuterLinkImage(string storeId)
3 {
4 ArrayList arr = new ArrayList();
5 List<string> strs = new List<string>();
6 strs.Add("aa");
7 strs.Add("aaa");
8 arr.Add(new DictionaryEntry("a", strs));
9 arr.Add(new DictionaryEntry("b", "bb"));
10 arr.Add(new DictionaryEntry("c", "cc"));
11
12 return arr;
13 }

这个结构应该还是算比较复杂了吧:) 调用之后会报如下的错误,网上搜索之后得知是返回的结构无法转换成xml结构导致的。

System.InvalidOperationException: 生成 XML 文档时出错。 ---> System.InvalidOperationException: 不应是类型 System.Collections.DictionaryEntry。使用 XmlInclude 或 SoapInclude 特性静态指定非已知的类型。

下面我们把方法改成如下,注意红色字体部分(这里将方法中用到的类型都加上了,每行一个,意思是告诉xml到时有这些类型节点,不知道这样表述对不对):

 1     [WebMethod]
2 [XmlInclude(typeof(ArrayList))]
3 [XmlInclude(typeof(DictionaryEntry))]
4 [XmlInclude(typeof(List<string>))]

5 public ArrayList GetOuterLinkImage(string storeId)
6 {
7 ArrayList arr = new ArrayList();
8 List<string> strs = new List<string>();
9 strs.Add("aa");
10 strs.Add("aaa");
11 arr.Add(new DictionaryEntry("a", strs));
12 arr.Add(new DictionaryEntry("b", "bb"));
13 arr.Add(new DictionaryEntry("c", "cc"));
14
15 return arr;
16 }

 于是,加上三行说明之后,不报错了,而且生成了xml结构如下:

<ArrayOfAnyType xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
<anyType xsi:type="DictionaryEntry">
<Key xsi:type="xsd:string">a</Key>
<Value xsi:type="ArrayOfString">
<string>aa</string>
<string>aaa</string>
</Value>
</anyType>
<anyType xsi:type="DictionaryEntry">
<Key xsi:type="xsd:string">b</Key>
<Value xsi:type="xsd:string">bb</Value>
</anyType>
<anyType xsi:type="DictionaryEntry">
<Key xsi:type="xsd:string">c</Key>
<Value xsi:type="xsd:string">cc</Value>
</anyType>
</ArrayOfAnyType>

这样应该就没问题了吧,好,我们到客户端调用试试,代码如下:

1 ArrayList arrlist = webService.GetOuterLinkImage(storeId);

靠,居然报错: 无法将类型“object[]”隐式转换为“System.Collections.ArrayList” ,于是你可能还会试试转成 DictionaryEntry[] ,结果怎样呢,还是不行,依然无法转换,那怎么办,只能转成object[]吗,那不是等于没转,不过,我们可以获取一下类型啊,如下
object[] objs = webService.GetOuterLinkImage(storeId);
Type t = objs.GetType();
监视一下 t 是啥东东来的

IsArray,对了,是一个Array,于是:Array arr = objs as Array; 转换成功

于是调用的时候就成了下面这样:

1             ArrayList arrlist = new ArrayList();
2 object[] objs = webService.GetOuterLinkImage(storeId);
3 Type t = objs.GetType();
4 Array arr = objs as Array;
5 foreach (var item in arr)
6 {
7 arrlist.Add(item);
8 }

这样就将对象转换过来了。

那么,arrlist里面是不是一个个 DictionaryEntry 类型呢?转一下看看,

            foreach (var item in arrlist)
            {
      //调试发现item并不是System.Collections.DictionaryEntry 而是 webService.DictionaryEntry类型,怎么回事呢,原来.net调用方法的时候反射成了一个自己的DictionaryEntry类,虽然结构是一样的,也有key,value ,但是还是只能将其转换成webService.DictionaryEntry,至于原因可能要看看webservice的机制,具体我也在探索中
            }

已经得到了DictionaryEntry,接下来就知道怎么做了吧。
over.

posted @ 2011-12-20 19:03  与卡  阅读(6336)  评论(1编辑  收藏  举报