如何将从jquery接收到的字符串转换为c动态对象
本文关键字:转换 字符串 对象 动态 jquery | 更新日期: 2023-09-27 18:26:43
如何在我的c#WEBMMETHOD中将json对象的字符串转换为动态字符串。。这样我就可以使用它来检索数据。
示例我的ajax调用
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'
}
有人能告诉我如何将来自ajax调用的对象作为字符串处理,并将其放入动态中并获取其详细信息吗提前感谢
JavaScriptSerializer将JSON字符串序列化为Dictionary,您不能仅将其强制转换为动态,否则您将丢失属性,您最好的选择是将字典转换为ExpandoObject,您可以轻松地将其强制转换为动态。这里有一个扩展方法:
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;
}
}
可以使用JavaScriptSerializer对象的DeserializeDynamic扩展方法将其反序列化为动态