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

asked Feb 6, 2015 at 7:11
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.

answered Feb 6, 2015 at 7:16

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": ....] };

answered Feb 6, 2015 at 7:28

Comments

2

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

answered Feb 6, 2015 at 7:13

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.