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
-
It's easy to find same question: stackoverflow.com/questions/2546138/…MacGyver– MacGyver2015年02月06日 07:14:09 +00:00Commented Feb 6, 2015 at 7:14
-
1possible duplicate of Parse JSON in C#Kutyel– Kutyel2015年02月06日 07:16:16 +00:00Commented Feb 6, 2015 at 7:16
3 Answers 3
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.
1 Comment
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
I strongly recommend you the NewtonSoft library for the .NET platform, is the best when talking of JSON serialization.