在Web Api控制器中将JSON反序列化为字典

5

我有这样一个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<int>> sendedData)
    {
        //code goes here
        return null;
    }

我总是得到 sendedData == null. 的结果。换句话说:我不知道如何将 JSON 反序列化为 (Dictionary<int, List<int>>

谢谢你的回答。


尝试解决这个问题了一段时间 - 然后阅读了这篇文章:https://dev59.com/u2445IYBdhLWcg3wwc2g - Yasser Shaikh
是的,看起来Web API上的JSON出了问题。 - Hot Licks
6个回答

1
您可以像这样发送数据:

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

控制器中的函数图像: 字典


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);

    }

1
尝试使用 String rawJson = Request.Content.ReadAsStringAsync().Result; - Hot Licks

0

试一下:

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

0

尝试使用:

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)
},

0

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

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

他的问题在于他正在构建的ajax调用,而不是服务器端。他使用了dataType(用于结果),而应该指定contentType为application/json。我已经在他的另一个类似的帖子中回答了他,并将答案复制到这里,供那些试图解决问题的人参考。其中一个线程应该被关闭为重复。 - Andrew

0

您在sendedData参数中缺少[FromBody]注释。请尝试以下代码:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接