项目需要用到外部提供的WebService,由于WebService的地址不固定,因此,采用动态调用的方式。
具体的调用方式,参考园子的文章:
1 动态调用 WebService
2 【转】动态调用WebService
代码没有什么问题,功能也可以实现,但是在传递复杂对象的时候,问题出来了。动态代理会自动生成自己的对象,无法通过强制转换实现调用。
解决办法:
1 传递对象为简单类型(string)
调用webservice方法成功之后,返回对象之前,对复杂对象进行xml序列化
返回对象中包含List结构
1: [Serializable]
2: public class QuestionEditList : BaseModel
3: {
4: private List<QuestionEditModel> _questionEditList = new List<QuestionEditModel>();
5:
6: public List<QuestionEditModel> QuesEditList
7: {
8: get { return _questionEditList ; }
9: set { _questionEditList = value; }
10: }
11: public QuestionEditList(List<QuestionEditModel> questionEditList)
12: {
13: this._questionEditList= questionEditList;
14:
15: }
16: public override void FromXml(string xml)
17: {
18: QuestionEditList question = (QuestionEditList)base.DeserializeFromXml(xml, typeof(QuestionEditList));
19: this.QuesEditList = question.QuesEditList;
20: }
21:
22: public override string ToXml()
23: {
24: return base.SerializeToXml(this);
25: }
26: }
序列化后的结果:
<QuestionEditList>
<QuesEditList>
<QuestionEditModel>
<MajorQuestionID>1</MajorQuestionID>
<MinorQuestionID>0</MinorQuestionID>
</QuestionEditModel>
<QuestionEditModel>
<MajorQuestionID>2</MajorQuestionID>
<MinorQuestionID>0</MinorQuestionID>
</QuestionEditModel>
<QuestionEditModel>
<MajorQuestionID>3</MajorQuestionID>
<MinorQuestionID>0</MinorQuestionID>
</QuestionEditModel>
</QuesEditList>
</QuestionEditList>
2 调用方拿到返回值,在进行xml反序列化
1: QuestionEditList questionList = new QuestionEditList();
2: questionList.FromXml(obj.ToString());
通过这样的方式传递,就可以获取到可以控制的对象。
序列化,反序列化方法
1 序列化
1: protected string SerializeToXml(object o)
2: {
3: XmlSerializer serializer = new XmlSerializer(o.GetType(), "");
4: MemoryStream w = new MemoryStream();
5: XmlTextWriter writer = new XmlTextWriter(w, Encoding.Default);
6: writer.Formatting = Formatting.None;
7: serializer.Serialize((XmlWriter)writer, o);
8: writer.Close();
9: return Encoding.Default.GetString(w.ToArray())
.Replace("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"", "")
.Replace("<?xml version=\"1.0\" encoding=\"gb2312\"?>", "");
10: }
2 反序列化
1: protected object DeserializeFromXml(string s, Type t)
2: {
3: XmlSerializer serializer = new XmlSerializer(t);
4: object obj2 = null;
5: XmlTextReader xmlReader = new XmlTextReader(s, XmlNodeType.Element, null);
6: obj2 = serializer.Deserialize(xmlReader);
7: xmlReader.Close();
8: return obj2;
9: }