1

This is my JSON and I am passing to the controller using $.Ajax

 [{"Id":["100"],"AdminId":2,"Type":"ReadWrite"},
 {"Id":["100"],"AdminId":3,"Type":"Read"}]

$.ajax({
            type: "POST",
            url: "/Home/Access",
            cache: false,
            data: { "data": UpdateData },
            async: true,
            success: function (response) {

            }
        });

 public JsonResult Access(string data)
    {
        var isUpdated = false;     
        return Json(isUpdated);
     }

How can I convert to generic list so that I can update my database. I need Id, AdminId, Type from JSON. I don't want to create a new class.

Amirhossein Mehrvarzi
  • 18,024
  • 7
  • 45
  • 70
Chatra
  • 2,989
  • 7
  • 40
  • 73
  • 5
    `I dont want to create a new class.` Why not? It doesn't take any time and is the most robust solution. – Matt Burland Mar 10 '15 at 19:59
  • Any reason why you don't want to create a new class? I guess your parameter could be `dynamic`, but why? – Tom Mar 10 '15 at 19:59
  • Also, your `id` is an array? Is it only supposed to ever have 1 member? Or can it have more than one? What is supposed to happen with more than 1? How would you map that? – Matt Burland Mar 10 '15 at 20:00
  • @MattBurland Because this is only one and small scenario. I want to keep it for one time use only. – Chatra Mar 10 '15 at 20:12
  • @WPFRookie: So, it's a one-time use. It's only a small class. It takes about 2 minutes and you have something robust and strongly typed. And in the future when that "one-time" use class suddenly becomes a "used all over the place" class, you are all set. – Matt Burland Mar 10 '15 at 20:17
  • http://stackoverflow.com/a/22191376/1743997 – Amirhossein Mehrvarzi Dec 19 '15 at 12:12

2 Answers2

0

Thanks for all the inputs. As other said, creating a class is the most robust one, we can do like below also without using class.

var oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
dynamic listData = oSerializer.DeserializeObject(data);

foreach (var obj in listData)
 {
    var Id = obj["Id"];
    var Type = obj["Type"];
 }
Chatra
  • 2,989
  • 7
  • 40
  • 73
  • 2
    If you don't have a reason to use dynamic, then probably better not to use it. You should use a class. – mason Mar 10 '15 at 20:36
0

You'll want to use JSON.NET to deserialize it as a JObject and then you can index into the object. You also probably could deserialize it as dynamic

I don't really recommend doing this just because you can.

Chris Marisic
  • 32,487
  • 24
  • 164
  • 258