【问题标题】:Deserialize JSON into dictionary in Web Api controller在 Web Api 控制器中将 JSON 反序列化为字典
【发布时间】:2014-05-24 04:10:00
【问题描述】:

我有这样的 JSON 字符串: '{"1":[1,3,5],"2":[2,5,6],"3":[5,6,8]}'

我想将其发送到 Web Api Controller 而不使用 ajax 请求进行更改:

   $.ajax({
        type: "POST",
        url: "Api/Serialize/Dict",
        data: JSON.stringify(sendedData),
        dataType: "json"
    });

在 Web Api 我有这样的方法:

    [HttpPost]
    public object Dict(Dictionary<int, List<int>> sendedData)
    {
        //code goes here
        return null;
    }

而且总是sendedData == null. 换句话说:我不知道如何将JSON反序列化为(Dictionary&lt;int, List&lt;int&gt;&gt;

谢谢你的回答。

【问题讨论】:

标签: javascript c# jquery json asp.net-web-api


【解决方案1】:

试试这个

 [HttpPost]
    public object Dict(Dictionary<int, List<int>> sendedData)
    {
       var d1 = Request.Content.ReadAsStreamAsync().Result;
       var rawJson = new StreamReader(d1).ReadToEnd();
       sendedData=Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<int, List<string>>>(rawJson);

    }

【讨论】:

  • 试试String rawJson = Request.Content.ReadAsStringAsync().Result;
【解决方案2】:

您可以这样发送数据:

{"sendedData":[{"key":"1","value":[1,3,5]},{"key":"2","value":[2,5,6]},{"key":"3","value":[5,6,8]}]}

控制器中的功能图像: Dict

【讨论】:

    【解决方案3】:

    试试看:

    Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<int, List<string>>>("{'1':[1,3,5],'2':[2,5,6],'3':[5,6,8]}");
    

    【讨论】:

      【解决方案4】:

      尝试使用:

      public ActionResult Parse(string text)
      {
          Dictionary<int, List<int>> dictionary = Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<int, List<int>>>(text);
          return Json(dictionary.ToString(), JsonRequestBehavior.AllowGet);
      }
      

      这适用于发送的数据在索引周围没有引号时:

      {1:[1,3,5],2:[2,5,6],3:[5,6,8]}
      

      还要确保在 Javascript 中发送对象:

      data: { 
          text: JSON.stringify(sendedData)
      },
      

      【讨论】:

        【解决方案5】:

        ajax调用时指定内容类型参数,dataType用于返回结果:

        $.ajax({ 
               type: "POST",
               url: "Api/Serialize/Dict", 
               contentType: "application/json; charset=utf-8", //!
               data: JSON.stringify(sendedData) 
        });
        

        【讨论】:

        • 他的问题是他正在构建的 ajax 调用,而不是服务器端。他使用了 dataType(用于结果),其中 contentType 应指定为 application/json。我已经在他的另一个类似的帖子中回答了他(他有两个),在这里为那些试图找出问题的人复制了答案。不过,其中一个线程应该作为重复关闭。
        【解决方案6】:

        您错过了 sendedData 参数中的 [FromBody] 注释。试试这个:

        [HttpPost]
        [Consumes("application/json")]
        [Produces("application/json")]
        public object Dict([FromBody] Dictionary<int, List<int>> sendedData)
        {
            //code goes here
            return null;
        }
        

        【讨论】:

          猜你喜欢
          • 2016-07-29
          • 2013-10-13
          • 2014-05-24
          • 2019-10-05
          • 1970-01-01
          • 2020-03-14
          • 2019-02-08
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多