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

2

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Mr. Dictus very helpful please add 0 after the +1 as i couldn't find the option in SO UI .
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": ....] };

Comments

2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.