.net 使用web服务传递具有复杂属性的对象
我有两门课:.net 使用web服务传递具有复杂属性的对象,.net,web-services,serialization,.net,Web Services,Serialization,我有两门课: public class testClass1 { public string Name { get; set; } public testClass2 testClass2Object { get; set; } } public class testClass2 { public testClass2() { } public testClass2(int i) { Te
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
属性的值
我尝试了[可序列化]
[xmlclude(typeof(testClass2))]
注释,但没有任何更改。有什么建议吗 如果我按原样运行代码并调用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
WebAPI具有快速、轻量级的输出,您可以将JSON和XML格式作为输出。非常健壮 如果删除
公共testClass2(inti)
构造函数会发生什么?如果您将声明更改为publicttestclass2(inttestproperty)
,又会怎样呢?(我问第二个问题,因为我知道ctor参数的实际名称可能会影响JSON序列化;但不确定它是否会影响其他序列化)。@Matthew Watson删除了构造函数,现在可以工作了,谢谢。@Matthew Watson如果我想发送它的对象,我不能让构造函数带有参数?哈!我不知道我在这个问题上悬赏了。:)