我有一个Web API
动作方法,该方法返回一个Dictionary<int, int>
作为响应:
[HttpPost("PostStats")]
public async Task<IActionResult> PostStats([FromBody]StatsBody body)
{
Dictionary<int, int> myDic= new Dictionary<int, int>();
... //Do something with body and myDic
return Ok(myDic);
}
通过HttpClient
调用该方法:
StatsBody stats = GetStatsBody();
using (var httpClient = new HttpClient { BaseAddress = new Uri(ROOT_ENDPOINT) })
{
// Serializes the content to be sent to the REST service
var content = new StringContent(JsonConvert.SerializeObject(stats), Encoding.UTF8, "application/json");
// Sends the request to the REST service
HttpResponseMessage response = await httpClient.PostAsync(URL, content);
// Gets the response as string
string output = await response.Content.ReadAsStringAsync();
if (response.StatusCode == HttpStatusCode.OK)
{
//Deserialize the response into a a Dictionary<int, int>
myDic = JsonConvert.DeserializeObject<Dictionary<int, int>>(output);
}
else
return BadRequest(output);
}
myDic = JsonConvert.DeserializeObject<Dictionary<int, int>>(output)
指令由于无法反序列化对象而给出了异常。
Newtonsoft.Json.JsonSerializationException: Error converting value "{"0":562,"1":563,"2":564}" to type 'System.Collections.Generic.Dictionary`2[System.Int32,System.Int32]'.
System.ArgumentException: Could not cast or convert from System.String to System.Collections.Generic.Dictionary`2[System.Int32,System.Int32].
即使我使用Dictionary<string, int>
或Dictionary<string, dynamic>
,也会出现异常。如果我检查变量output
,则其内容格式如下:
"{\"0\":565,\"1\":566,\"2\":567}"
这实际上不是有效的JSON格式。唯一可以通过使用以下方法获得正确的反序列化:
string temp = JsonConvert.DeserializeObject<string>(output);
myDic = JsonConvert.DeserializeObject<Dictionary<int, int>>(temp);
我在做什么错,如何获得更清晰的解决方案?
PS:
如果我使用Typescript
客户端,然后使用JSON.parse
将响应解析为一个关联数组(基本上是一个字典),则没有问题。