17
votes

I have this method that is returning Dictionary as a JsonResult when I try to deserialize this Dictionary in Ajax I am getting this error:

This is my method in MVC:

[HttpPost]
public JsonResult GetCalculateAmortizationSchedule()
{
      var data =.....
      var httpClient = new HttpClient();
      var response = httpClient.PostAsJsonAsync("http://localhost:62815/v1/APR/CalculateAmortizationSchedule", data).Result;
      var returnValue = response.Content.ReadAsAsync<Dictionary<int, AmItem>>().Result;
      return Json(returnValue);
}

This is error:

Type 'System.Collections.Generic.Dictionary`2[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[ConnectionMappingSample.Models.AmItem, ConnectionMappingSample, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]]' is not supported for serialization/deserialization of a dictionary, keys must be strings or objects.

2
Dictionary<int, AmItem>: The key is int. It's telling you that "keys must be strings or objects". What's your question?15ee8f99-57ff-4f92-890c-b56153
You should make your action async and await instead of using .Result.SLaks

2 Answers

17
votes

This is your dictionary: Dictionary<int, AmItem>

This is what your dictionary should be: Dictionary<string, AmItem>

0
votes

I had the same error, but I found it to be a bit strange... Why wouldn't Javascript support integers as keys for dictionaries right?

So my solution was to just transform the dictionary into a list before deserialization.

If dict is your dictionary:

var JSdict = @Html.Raw(Json.Encode(dict.ToList()));