2014-06-18 75 views
0

我无法成功将List<StringDictionary>>的已填充实例从Web API控制器返回到C#控制台应用程序。下面是详细信息...Web Api - 返回字典

的Web API代码:

[HttpPost] 
    public async Task<HttpResponseMessage> Get(IEnumerable<long> ids) 
    { 
      var results = [assume populated instance of List<StringDictionary>>] 

      return Request.CreateResponse<List<StringDictionary>>(HttpStatusCode.OK, results); 

    } 

我有下面的客户端代码:

 using (var httpClient = new HttpClient { BaseAddress = new Uri(baseAddress) }) 
     { 

      var httpResponse = httpClient.PostAsJsonAsync<long[]>("api/promotions", mockIds).Result; 

      if (httpResponse.IsSuccessStatusCode) 
      { 
       var content = httpResponse.Content.ReadAsAsync<List<StringDictionary>>().Result; ***** DOES NOT WORK **** 

      } 

     } 

我得到以下错误:

{"Cannot create and populate list type System.Collections.Specialized.StringDictionary. Path '[0]', line 1, position 2."} 

我在这里错过了什么明显的事实?

更新 - 有趣的是,如果我将StringDictionary更改为Dictionary,它的效果很好。

回答

0

区别在于DeSerialization。 JSON解串器无法反序列化您发送的格式。如果你只是尝试发送单个对象,你会得到这个错误:Cannot create and populate list type System.Collections.Specialized.StringDictionary.

link可以帮助你得到更多的理解。

这里是序列化的Dictionary和String字典的JSON表示。

字典

[ 
    { 
     "1": "A", 
     "4": "G" 
    }, 
    { 
     "1": "A", 
     "3": "B" 
    } 
] 

字符串字典

[ 
[ 
    { 
     "_key": "4", 
     "_value": "G" 
    }, 
    { 
     "_key": "1", 
     "_value": "A" 
    } 
], 
[ 
    { 
     "_key": "3", 
     "_value": "B" 
    }, 
    { 
     "_key": "1", 
     "_value": "A" 
    } 
] 
]