【问题标题】:Pass object with complex property with web service使用 Web 服务传递具有复杂属性的对象
【发布时间】:2013-03-16 05:12:32
【问题描述】:

我有 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;
    }

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

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

【问题讨论】:

  • 如果删除public testClass2(int i) 构造函数会发生什么?如果您将声明更改为public testClass2(int testProperty ) 会怎样? (我问第二个是因为我知道 ctor 参数的实际名称会影响 JSON 序列化;但不确定它是否会影响其他序列化)。
  • @Matthew Watson 删除了构造函数,现在可以使用了,谢谢。
  • @Matthew Watson 如果我想发送它的对象,我不能有带参数的构造函数?

标签: .net web-services serialization


【解决方案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>

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

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

【讨论】:

  • 哈!我没有意识到我已经在这个问题上投入了赏金。 :)
【解决方案2】:

我运行了您的代码,结果符合我的预期。你 应该使用 xml 解析从 testclass2 中获取数据。

编辑

我建议使用 Web API 而不是过时的 ASMX,后者使用 SOAP 在输出中生成大量非结构化、无模式的 XML。

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

【讨论】:

    猜你喜欢
    • 2011-04-10
    • 2014-10-28
    • 2018-10-06
    • 2012-08-06
    • 1970-01-01
    • 1970-01-01
    • 2011-01-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多