how can i convert a string which is a json object to dynamic in my c# WEBMETHOD..so that i can use it retrieve data.
example my ajax call
function do_save_data()
{
$.ajax({
type:"POST",
url:"../mymethods/test.aspx/SaveUser",
data:"{'profile':'"+objrecieved+"'}",
contentType:"application/json; charset=utf-8",
success:function(msg){}
});
}
[WebMethod]
public void save data(object profile)
{
JavaScriptSerializer _myserliaser=new JavaScriptSerializer();
dynamic data=(dynamic)_myserliaser.DeseralizeObject(profile);
//problem here is it is taking it as a string.hence when it try
string name=data.name.ToString();
//error 'string' does not contain a definition for 'name'
}
can anyone please tell me how to handle object that comes from ajax call as string and put it into dynamic and get its details Thanks in advance
JavaScriptSerializer seralizes JSON string to a Dictionary, you can't just cast it to dynamic, otherwise you lose the properties, your best bet is to convert the dictionary to an ExpandoObject which you can easily cast to dynamic. Here's an extension method to do so:
public static class JavaScriptSerializerExtension
{
public static dynamic DeserializeDynamic(this JavaScriptSerializer serializer, string value)
{
var dic = serializer.Deserialize<IDictionary<string, object>>(value);
return ToExpando(dic);
}
private static ExpandoObject ToExpando(IDictionary<string, object> dic)
{
var expando = new ExpandoObject() as IDictionary<string, object>;
foreach (var item in dic)
{
var prop = item.Value as IDictionary<string, object>;
expando.Add(item.Key, prop == null ? item.Value : ToExpando(prop));
}
return (ExpandoObject)expando;
}
}
you can use DeserializeDynamic extension method of the JavaScriptSerializer object to deserialize to dynamic
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.