在Web Api控制器中将JSON反序列化为字典
我有这样的JSON字符串: '{"1":[1,3,5],"2":[2,5,6],"3":[5,6,8]}'
我想将其发送到Web Api控制器而不使用ajax请求更改:
$.ajax({ type: "POST", url: "Api/Serialize/Dict", data: JSON.stringify(sendedData), dataType: "json" });
在Web Api我有这样的方法:
[HttpPost] public object Dict(Dictionary<int, List> sendedData) { //code goes here return null; }
总是sendedData == null.
换句话说:我不知道如何将JSON反序列化为(Dictionary<int, List>
。
谢谢你的答案。
试试这个
[HttpPost] public object Dict(Dictionary> sendedData) { var d1 = Request.Content.ReadAsStreamAsync().Result; var rawJson = new StreamReader(d1).ReadToEnd(); sendedData=Newtonsoft.Json.JsonConvert.DeserializeObject>>(rawJson); }
试试吧:
Newtonsoft.Json.JsonConvert.DeserializeObject>>("{'1':[1,3,5],'2':[2,5,6],'3':[5,6,8]}");
尝试使用:
public ActionResult Parse(string text) { Dictionary> dictionary = Newtonsoft.Json.JsonConvert.DeserializeObject>>(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) },
执行ajax调用时指定内容类型参数,dataType用于返回结果:
$.ajax({ type: "POST", url: "Api/Serialize/Dict", contentType: "application/json; charset=utf-8", //! data: JSON.stringify(sendedData) });