如何在c#wcf中将不同类的对象包含到一个列表中,并将它们作为json返回?
基本上,我们现在正试图找到一种使用C#WCF生成json的方法,如下所示如何在c#wcf中将不同类的对象包含到一个列表中,并将它们作为json返回?,c#,json,wcf,serialization,C#,Json,Wcf,Serialization,基本上,我们现在正试图找到一种使用C#WCF生成json的方法,如下所示 [{Test1Class},{Test2Class}] 我试过以下方法 [DataContract] public class TestBaseClass { [DataMember] public string baseproperty { get; set; } } [DataContract] public class Test1Class:T
[{Test1Class},{Test2Class}]
我试过以下方法
[DataContract]
public class TestBaseClass
{
[DataMember]
public string baseproperty { get; set; }
}
[DataContract]
public class Test1Class:TestBaseClass
{
[DataMember]
public string test1property { get; set; }
}
[DataContract]
public class Test2Class:TestBaseClass
{
[DataMember]
public string test2property { get; set; }
}
//testing returns
[WebInvoke(Method = "GET", UriTemplate = "history/testtest", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
public List<TestBaseClass> ddd()
{
List<TestBaseClass> result = new List<TestBaseClass>();
result.Add(new Test1Class());
result.Add(new Test2Class());
return result;
}
[DataContract]
公共类TestBaseClass
{
[数据成员]
公共字符串baseproperty{get;set;}
}
[数据合同]
公共类Test1Class:TestBaseClass
{
[数据成员]
公共字符串test1property{get;set;}
}
[数据合同]
公共类Test2Class:TestBaseClass
{
[数据成员]
公共字符串test2property{get;set;}
}
//测试回报
[WebInvoke(Method=“GET”,UriTemplate=“history/testtest”,RequestFormat=WebMessageFormat.Json,ResponseFormat=WebMessageFormat.Json)]
公共列表ddd()
{
列表结果=新列表();
添加(新Test1Class());
添加(新Test2Class());
返回结果;
}
但它不起作用,什么也没有回报。无错误无任何内容。WCF要求事先声明对象图中遇到的所有类型。最常见的情况是,这种情况通过类型的数据协定元数据发生,该元数据枚举要序列化的属性的类型和名称。当需要多态性时,正如在类层次结构中一样,您需要使用以下命令声明所需的子类型:
或者通过将已知类型的列表传递给:
伟大的如果有一种方法可以隐藏_类型或类型提示,它将是完美的。有吗?@shawhu-不确定,但我找到了
[DataContract]
[KnownType(typeof(Test1Class))]
[KnownType(typeof(Test2Class))]
public class TestBaseClass
{
[DataMember]
public string baseproperty { get; set; }
}
var serializer = new DataContractJsonSerializer(typeof(List<TestBaseClass>), new[] { typeof(Test1Class), typeof(Test2Class) });
[
{
"__type": "Test1Class:#Question33569121",
"baseproperty": null,
"test1property": null
},
{
"__type": "Test2Class:#Question33569121",
"baseproperty": null,
"test2property": null
}
]