简体   繁体   English

无法返回WCF中的词典列表

[英]unable to return List of dictionary in WCF

I am new in WCF. 我是WCF的新手。 I am trying to return list of dictionary in wcf. 我正在尝试返回wcf中的字典列表。

Here is my code. 这是我的代码。

 public class Service1 : IService1
 {
   public List<Dictionary<string, object>> GetData(string query)
    {
          List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
          ...
          ...
          return rows;
    }

 }

public interface IService1
{
    [WebGet()]
    [OperationContract]
    List<Dictionary<string, object>> GetData();
}

If I return return string it will work properly I want to return list like this. 如果我返回return字符串,它将正常工作,我想这样返回列表。

You have to create class and set attribute KnownType . 您必须创建类并设置属性KnownType

 [DataContract]
[KnownType(typeof(List<Dictionary<string, object>>))]
public class Foo
{
    [DataMember]
    public IDictionary<String, Object> Inputs { get; set; }
}

Now instead List<Dictionary<string, object>> use List<Foo> You can do like this sample. 现在List<Dictionary<string, object>>使用List<Foo>代替List<Dictionary<string, object>>使用此示例。

IService 服务

        [OperationContract]
   [WebInvoke(Method = "GET",
   ResponseFormat = WebMessageFormat.Json,
   BodyStyle = WebMessageBodyStyle.Bare,
   UriTemplate = "GetData")]
    List<Foo> GetData();

Service 服务

    public List<Foo> GetData()
    {
        List<Foo> rows = new List<Foo>();
        var x = new Dictionary<string, object>();
        x.Add("sss","sss");
        x.Add("zzz", "zzz");
        x.Add("aaa", "aaa");
        var z = new Foo();
       z.Inputs = x;

        rows.Add(z);
        rows.Add(z);
        return rows;
    }

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM