Deserialize JSON to Dictionary in Web Api Controller

I have a JSON line like this: '{"1":[1,3,5],"2":[2,5,6],"3":[5,6,8]}'

I want to send it to Web Api Controller without modification using an ajax request:

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

In Web Api, I have a method like this:

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

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

Thanks for the answer.

+4
source share
6 answers

try it

 [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
source

You can send data as follows:

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

Function Image in Controller: Dict

+1
source

:

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

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

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

You missed the annotation [FromBody]in the sendedData parameter. Try it:

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

Source: https://habr.com/ru/post/1535929/


All Articles