Iterate through dynamic form object Iterate through dynamic form object asp.net asp.net

Iterate through dynamic form object


If you get a json from the argument, you could convert it to an Dictionary<string, dynamic> where the string key is the name of the property and the dynamic is a value that can assume any type. For sample:

var d = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(form);var username = d["username"];

You also could loop between Keys property from the Dictionary<>:

foreach(var key in d.Keys){   // check if the value is not null or empty.   if (!string.IsNullOrEmpty(d[key]))    {      var value = d[key];      // code to do something with    }}


This is quite old, but I came across this and am wondering why the following was not proposed:

var data = (IDictionary<string, object>)form;


You can use JavaScriptSerializer and dynamic object:

JavaScriptSerializer serializer = new JavaScriptSerializer();dynamic myDynamicObject = serializer.DeserializeObject(json);

For example, if you want to loop through myDynamicObject["users"]:

foreach (KeyValuePair<string, dynamic> user in myDynamicObject["users"]){    Console.WriteLine(user.Key+": "+user.Value["username"]);    Console.WriteLine(user.Key+": "+user.Value["email"]);}