0

I have a json string which is submitted on controller using Model string value property. I want to convert this json string into c# generic list object.

Below is my json string

{
    "MLIDandRackPosition": [
        {
            "MLID": "27",
            "PositionInRack": "3"
        },
        {
            "MLID": "24",
            "PositionInRack": "4"
        }
    ]
}

Below is my class

  public class MLIDandRackPosition
    {
        public int MLID { get; set; }
        public int PositionInRack { get; set; }
    }

I want a List of MLIDandRackPosition class from json string on controller action method.

Please help

Prashant Mehta
  • 484
  • 2
  • 11
  • 30
  • It's easy to find same question: http://stackoverflow.com/questions/2546138/deserializing-json-data-to-c-sharp-using-json-net – MacGyver Feb 06 '15 at 07:14
  • 1
    possible duplicate of [Parse JSON in C#](http://stackoverflow.com/questions/1212344/parse-json-in-c-sharp) – Kutyel Feb 06 '15 at 07:16

3 Answers3

4

With JSON.NET you can do that in a single line:

MLIDandRackPosition myObj = JsonConvert.DeserializeObject<MLIDandRackPosition>(myString);

See http://www.newtonsoft.com/json/help/html/Introduction.htm for more about JSON.NET.

Roy Dictus
  • 32,551
  • 8
  • 60
  • 76
2

I strongly recommend you the NewtonSoft library for the .NET platform, is the best when talking of JSON serialization.

Kutyel
  • 8,575
  • 3
  • 30
  • 61
2

Your object will bind correctly to

public ActionResult SomeAction(IEnumerable<MLIDandRackPosition> MLIDandRackPosition)

If you set the following ajax parameters

var data = { "MLIDandRackPosition": [ { "MLID": "27", "PositionInRack": "3" }, { "MLID": "24", "PositionInRack": "4" } ] };

$.ajax({
  ...
  traditional: true,
  contentType: "application/json; charset=utf-8",
  data: JSON.stringify(data)
})

although I would recommend changing the parameter name (to say model) and var data = { "model": [ { "MLID": ....] };