Deserialize JSON into dictionary in Web Api contro

2019-06-24 07:10发布

I have such JSON string: '{"1":[1,3,5],"2":[2,5,6],"3":[5,6,8]}'

I want to send it to the Web Api Controller without changing using ajax request:

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

In Web Api I have such method:

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

And always sendedData == null. Another words: I don't know how to deserialize JSON into (Dictionary<int, List<int>>.

Thank you for answer.

5条回答
孤傲高冷的网名
2楼-- · 2019-06-24 07:42

Try this

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

    }
查看更多
地球回转人心会变
3楼-- · 2019-06-24 07:43

You can send the data like this:

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

Image of the function in the controller: Dict

查看更多
贼婆χ
4楼-- · 2019-06-24 08:01

specify the content type parameter when performing ajax call, dataType is for return result:

$.ajax({ 
       type: "POST",
       url: "Api/Serialize/Dict", 
       contentType: "application/json; charset=utf-8", //!
       data: JSON.stringify(sendedData) 
});
查看更多
狗以群分
5楼-- · 2019-06-24 08:06

Try it:

Newtonsoft.Json.JsonConvert.DeserializeObject<Dictionary<int, List<string>>>("{'1':[1,3,5],'2':[2,5,6],'3':[5,6,8]}");
查看更多
我命由我不由天
6楼-- · 2019-06-24 08:07

Try using:

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

This works when the sent data doesn't have quotes around the indices:

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

Also make sure that you send an object in the Javascript:

data: { 
    text: JSON.stringify(sendedData)
},
查看更多
登录 后发表回答