2014-06-18 92 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" 
    } 
] 
]