【问题标题】:How to include objects of different classes into a list in c# wcf and return them as json?如何将不同类的对象包含到c#wcf中的列表中并将它们作为json返回?
【发布时间】:2015-11-06 14:32:47
【问题描述】:

基本上,我们现在正在尝试找出一种使用 C# WCF 生成 json 的方法,就像这样。

[{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;
    }

它不起作用,没有任何返回。没有错误没有什么。

【问题讨论】:

    标签: c# json wcf serialization


    【解决方案1】:

    WCF 的data contract serializers 要求事先声明对象图中遇到的所有类型。最常见的情况是通过类型的数据协定元数据发生,该元数据枚举要序列化的属性的类型和名称。当需要多态性时,就像在您的类层次结构中一样,您需要使用 KnownTypeAttribute 声明预期的子类型:

    [DataContract]
    [KnownType(typeof(Test1Class))]
    [KnownType(typeof(Test2Class))]
    public class TestBaseClass
    {
        [DataMember]
        public string baseproperty { get; set; }
    }
    

    或通过将已知类型列表传递给data contract serializer

    var serializer = new DataContractJsonSerializer(typeof(List<TestBaseClass>), new[] { typeof(Test1Class), typeof(Test2Class) });
    

    完成此操作后,WCF 的 DataContractJsonSerializer 将为您的列表生成 JSON,其中 type hints 指示实际序列化的类型:

    [
      {
        "__type": "Test1Class:#Question33569121",
        "baseproperty": null,
        "test1property": null
      },
      {
        "__type": "Test2Class:#Question33569121",
        "baseproperty": null,
        "test2property": null
      }
    ]
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-15
    • 1970-01-01
    • 2022-08-25
    相关资源
    最近更新 更多