5

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.

Liam
  • 27,717
  • 28
  • 128
  • 190
Taras Strizhyk
  • 135
  • 1
  • 2
  • 9

6 Answers6

1

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

    }
Nilesh Gajare
  • 6,302
  • 3
  • 42
  • 73
1

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

0

Try it:

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

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)
},
Re Captcha
  • 3,125
  • 2
  • 22
  • 34
0

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) 
});
Andrew
  • 3,648
  • 1
  • 15
  • 29
  • His problem is the ajax call he's building, not the server side. He used dataType(which is for result), where as contentType should be specified as application/json. I've already answered him in his other similar thread(he has two), copied the answer here for those who were trying to figure out the issue. One of those threads should be closed as duplicate though. – Andrew Apr 11 '14 at 07:31
0

You missed the [FromBody] annotation in the sendedData param. Try this:

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