【问题标题】:Dictionary is not supported for serialization/deserialization of a dictionary, keys must be strings or objects字典的序列化/反序列化不支持字典,键必须是字符串或对象
【发布时间】:2017-10-23 16:50:54
【问题描述】:

当我尝试在 Ajax 中反序列化此 Dictionary 时,我有此方法将 Dictionary 作为 JsonResult 返回我收到此错误:

这是我在 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);
}

这是错误:

键入'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]]' 不支持字典的序列化/反序列化,键必须是字符串或对象。

【问题讨论】:

  • Dictionary&lt;int, AmItem&gt;: 关键是 int。它告诉您“键必须是字符串或对象”。你有什么问题?
  • 您应该使用asyncawait 而不是使用.Result

标签: c# .net dictionary serialization


【解决方案1】:

这是你的字典:Dictionary&lt;int, AmItem&gt;

你的字典应该是这样的:Dictionary&lt;string, AmItem&gt;

【讨论】:

    【解决方案2】:

    我遇到了同样的错误,但我发现它有点奇怪......为什么 Javascript 不支持整数作为字典的键?

    所以我的解决方案是在反序列化之前将字典转换为列表

    如果dict 是您的字典:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-10-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多