0

I am POSTing a JSON object to a controller action:

            $.ajax({
                url: "/path/to/action",
                type: "POST",
                dataType: "json",
                data: {
                        name: "John Doe",
                        phone: "2323454543",
                        skills: {
                            code: "php",
                            design: "photoshop"
                            }
                        }
            });

How can I map this data to some kind of key-value pair object? In PHP, these get mapped to an associative array invisibly. I would like to be able to access properties like this:

SomeDynamicType data = ...//something here to prepare json data
string codeSkills = data.skills.code; //codeSkills should = "php"

I'm not interested in model binding since these value do not correspond to a model - they are arbitrary.

orourkedd
  • 6,201
  • 5
  • 43
  • 66

2 Answers2

0

Try using JSON.NET, this library parses JSON into a dictionary-like structure. It is used as follows:

JObject rss = JObject.Parse(json);
string codeSkills = (string)rss["skills"]["code"];
ColinE
  • 68,894
  • 15
  • 164
  • 232
0

In your .ajax call stringify Json:

data: {
                json:
                    JSON.stringify({
                        name: "John Doe",
                        phone: "2323454543",
                        skills: {
                            code: "php",
                            design: "photoshop"
                        }
                    })
            }

And accessing properties how you wanted in your controller:

        [HttpPost]
        public JsonResult Action(string json)
        {
            dynamic data = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(json);
            string codeSkills = data.skills.code;
...

codeSkills is "php" string.

Newtonsoft Json library is available since .NET 4, if I recall correct.

Lars
  • 1,699
  • 2
  • 22
  • 32