使用Web服务传递具有复杂属性的对象

时间:2013-03-26 11:58:17

标签: .net web-services serialization

我有2个班级:

    public class testClass1
    {
        public string Name { get; set; }
        public testClass2 testClass2Object { get; set; }
    }

    public class testClass2
    {
        public testClass2() { }

        public testClass2(int i) { TestProperty = i; }

        public int TestProperty { get; set; }
    }

我想用webMethod返回第一堂课的对象:

    [WebMethod]
    public testClass1 testMethod()
    {
        testClass1 test = new testClass1();
        test.Name = "stackoverflow";
        test.testClass2Object = new testClass2(2);
        return test;
    }

但我没有从testClass2对象获取testClass1属性的值。

我尝试了[Serializable] [XmlInclude(typeof(testClass2))]注释,但没有任何改变。有什么建议?

2 个答案:

答案 0 :(得分:1)

如果我“按原样”运行代码并调用testMethod(),我得到......

<testClass1 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns="http://tempuri.org/">
     <Name>stackoverflow</Name>
     <testClass2Object>
          <TestProperty>2</TestProperty>
     </testClass2Object>
</testClass1>

你期待不同的东西吗?也许我错过了什么。

如果这是一个更大项目的一部分,也许可以尝试将此代码放入一个新项目,看看它是否可能是一个设置或其他配置类型的问题。

答案 1 :(得分:0)

  

我运行你的代码,输出是我所期待的。您   应该使用xml解析从testclass2获取数据。

修改

我建议使用Web API而不是过时的ASMX,它使用SOAP在输出中生成非结构化的无架构数量的XML。

Web-API具有快速轻量级输出,您可以同时使用JSON和XML格式作为输出。非常健壮!