/// <summary> /// Converts an JSON string into an NET object. /// </summary> /// <param name="json">The JSON string representation.</param> /// <param name="type">The type to convert the string to.</param> /// <returns>Returns a .NET object.</returns> /// <example> /// using System; /// using AjaxPro; /// namespace Demo /// { /// public class WebForm1 : System.Web.UI.Page /// { /// private void Page_Load(object sender, System.EventArgs e) /// { /// string json = "[1,2,3,4,5,6]"; /// object o = JavaScriptDeserializer.Deserialize(json, typeof(int[]); /// if(o != null) /// { /// foreach(int i in (int[])o) /// { /// Response.Write(i.ToString()); /// } /// } /// } /// } /// } /// </example> public static object DeserializeFromJson(string json, Type type) { JSONParser p = new JSONParser(); IJavaScriptObject o = p.GetJSONObject(json); return(JavaScriptDeserializer.Deserialize(o, type)); }
/// <summary> /// Converts an IJavaScriptObject into an NET object. /// </summary> /// <param name="o">The IJavaScriptObject object to convert.</param> /// <param name="t"></param> /// <returns>Returns a .NET object.</returns> public override object Deserialize(IJavaScriptObject o, Type t) { #if (!JSONLIB) if (!Utility.Settings.OldStyle.Contains("allowNumberBooleanAsString")) #endif { if (o is JavaScriptNumber) { return(JavaScriptDeserializer.Deserialize(o, typeof(Int64))); } else if (o is JavaScriptBoolean) { return(JavaScriptDeserializer.Deserialize(o, typeof(Boolean))); } } if (t == typeof(char)) { string s = o.ToString(); if (s.Length == 0) { return('\0'); } return(s[0]); } return(o.ToString()); }
/// <summary> /// HTMLs the control from string. /// </summary> /// <param name="html">The HTML.</param> /// <param name="type">The type.</param> /// <returns></returns> internal static HtmlControl HtmlControlFromString(string html, Type type) { if (!typeof(HtmlControl).IsAssignableFrom(type)) { throw new InvalidCastException("The target type is not a HtmlControlType"); } JavaScriptDeserializer.ThrowExceptionIfNotCustomTypeDeserializationAllowed(type); html = AddRunAtServer(html, (Activator.CreateInstance(type) as HtmlControl).TagName); if (type.IsAssignableFrom(typeof(HtmlSelect))) { html = CorrectAttributes(html); } Control o = HtmlControlConverterHelper.Parse(html); if (o.GetType() == type) { return(o as HtmlControl); } else { foreach (Control con in o.Controls) { if (con.GetType() == type) { return(con as HtmlControl); } } } return(null); }
/// <summary> /// Deserializes the custom object. /// </summary> /// <param name="o">The o.</param> /// <param name="type">The type.</param> /// <returns></returns> internal static object DeserializeCustomObject(JavaScriptObject o, Type type) { object c = Activator.CreateInstance(type); MemberInfo[] members = type.GetMembers(BindingFlags.GetField | BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance); foreach (MemberInfo memberInfo in members) { if (memberInfo.MemberType == MemberTypes.Field) { if (o.Contains(memberInfo.Name)) { FieldInfo fieldInfo = (FieldInfo)memberInfo; fieldInfo.SetValue(c, JavaScriptDeserializer.Deserialize((IJavaScriptObject)o[fieldInfo.Name], fieldInfo.FieldType)); } } else if (memberInfo.MemberType == MemberTypes.Property) { if (o.Contains(memberInfo.Name)) { PropertyInfo propertyInfo = (PropertyInfo)memberInfo; if (propertyInfo.CanWrite) { propertyInfo.SetValue(c, JavaScriptDeserializer.Deserialize((IJavaScriptObject)o[propertyInfo.Name], propertyInfo.PropertyType), new object[0]); } } } } return(c); }
/// <summary> /// Converts an IJavaScriptObject into an NET object. /// </summary> /// <param name="o">The IJavaScriptObject object to convert.</param> /// <param name="t"></param> /// <returns>Returns a .NET object.</returns> public override object Deserialize(IJavaScriptObject o, Type t) { JavaScriptObject ht = o as JavaScriptObject; if (ht == null) { throw new NotSupportedException(); } if (!ht.Contains("Columns") || !(ht["Columns"] is JavaScriptArray) || !ht.Contains("Rows") || !(ht["Rows"] is JavaScriptArray)) { throw new NotSupportedException(); } JavaScriptArray columns = (JavaScriptArray)ht["Columns"]; JavaScriptArray rows = (JavaScriptArray)ht["Rows"]; DataTable dt = new DataTable(); DataRow row = null; Type colType; JavaScriptArray column; if (ht.Contains("TableName") && ht["TableName"] is JavaScriptString) { dt.TableName = ht["TableName"].ToString(); } for (int i = 0; i < columns.Count; i++) { column = (JavaScriptArray)columns[i]; colType = Type.GetType(column[1].ToString(), true); dt.Columns.Add(column[0].ToString(), colType); } JavaScriptArray cols = null; object obj; for (int y = 0; y < rows.Count; y++) { // if(!(r is JavaScriptArray)) // continue; cols = (JavaScriptArray)rows[y]; row = dt.NewRow(); for (int i = 0; i < cols.Count; i++) { //row[i] = JavaScriptDeserializer.Deserialize((IJavaScriptObject)cols[i], dt.Columns[i].DataType); obj = JavaScriptDeserializer.Deserialize((IJavaScriptObject)cols[i], dt.Columns[i].DataType); row[i] = (obj == null) ? DBNull.Value : obj; } dt.Rows.Add(row); } return(dt); }
/// <summary> /// Converts an IJavaScriptObject into an NET object. /// </summary> /// <param name="o">The IJavaScriptObject object to convert.</param> /// <param name="t"></param> /// <returns>Returns a .NET object.</returns> public override object Deserialize(IJavaScriptObject o, Type t) { if (!AjaxPro.Utility.Settings.OldStyle.Contains("renderJsonCompliant")) { if (!(o is JavaScriptArray)) { throw new NotSupportedException(); } JavaScriptArray a = (JavaScriptArray)o; for (int i = 0; i < a.Count; i++) { if (!(a[i] is JavaScriptArray)) { throw new NotSupportedException(); } } IDictionary d = (IDictionary)Activator.CreateInstance(t); object key; object value; JavaScriptArray aa; for (int i = 0; i < a.Count; i++) { aa = (JavaScriptArray)a[i]; Type keyType = Type.GetType(((JavaScriptString)aa[2]).ToString()); Type valueType = Type.GetType(((JavaScriptString)aa[3]).ToString()); JavaScriptDeserializer.ThrowExceptionIfNotCustomTypeDeserializationAllowed(keyType); JavaScriptDeserializer.ThrowExceptionIfNotCustomTypeDeserializationAllowed(valueType); key = JavaScriptDeserializer.Deserialize((IJavaScriptObject)aa[0], keyType); value = JavaScriptDeserializer.Deserialize((IJavaScriptObject)aa[1], valueType); d.Add(key, value); } return(d); } if (!(o is JavaScriptObject)) { throw new NotSupportedException(); } JavaScriptObject oa = (JavaScriptObject)o; IDictionary od = (IDictionary)Activator.CreateInstance(t); foreach (string key in oa.Keys) { od.Add(key, JavaScriptDeserializer.Deserialize(oa[key], typeof(string))); } return(od); }
/// <summary> /// Retreives the parameters. /// </summary> /// <returns></returns> public override object[] RetreiveParameters() { ParameterInfo[] pi = method.GetParameters(); object[] args = new object[pi.Length]; // initialize default values for (int i = 0; i < pi.Length; i++) { args[i] = pi[i].DefaultValue; } string v = context.Request["data"]; // If something went wrong or there are no arguments // we can return with the empty argument array. if (v == null || pi.Length == 0 || v == "{}") { return(args); } if (context.Request.ContentEncoding != System.Text.Encoding.UTF8) { v = System.Text.Encoding.UTF8.GetString(context.Request.ContentEncoding.GetBytes(v)); } hashCode = v.GetHashCode(); // check if we have to decrypt the JSON string. if (Utility.Settings != null && Utility.Settings.Security != null) { v = Utility.Settings.Security.SecurityProvider.Decrypt(v); } context.Items.Add(Constant.AjaxID + ".JSON", v); JavaScriptObject jso = (JavaScriptObject)JavaScriptDeserializer.DeserializeFromJson(v, typeof(JavaScriptObject)); for (int i = 0; i < pi.Length; i++) { //if (pi[i].ParameterType.IsAssignableFrom(jso[pi[i].Name].GetType())) //{ // args[i] = jso[pi[i].Name]; //} //else { args[i] = JavaScriptDeserializer.Deserialize((IJavaScriptObject)jso[pi[i].Name], pi[i].ParameterType); } } return(args); }
/// <summary> /// Converts an IJavaScriptObject into an NET object. /// </summary> /// <param name="o">The IJavaScriptObject object to convert.</param> /// <param name="t"></param> /// <returns>Returns a .NET object.</returns> public override object Deserialize(IJavaScriptObject o, Type t) { //return Enum.Parse(type, o.ToString()); object enumValue = JavaScriptDeserializer.Deserialize(o, Enum.GetUnderlyingType(t)); if (!Enum.IsDefined(t, enumValue)) { throw new ArgumentException("Invalid value for enum of type '" + t.ToString() + "'.", "o"); } return(Enum.ToObject(t, enumValue)); }
/// <summary> /// Converts an IJavaScriptObject into an NET object. /// </summary> /// <param name="o">The IJavaScriptObject object to convert.</param> /// <param name="t"></param> /// <returns>Returns a .NET object.</returns> public override object Deserialize(IJavaScriptObject o, Type t) { JavaScriptArray list = o as JavaScriptArray; if (list == null) { throw new NotSupportedException(); } if (t.IsArray) { Type type = Type.GetType(t.AssemblyQualifiedName.Replace("[]", "")); Array a = Array.CreateInstance(type, (list != null ? list.Count : 0)); try { if (list != null) { for (int i = 0; i < list.Count; i++) { object v = JavaScriptDeserializer.Deserialize(list[i], type); a.SetValue(v, i); } } } catch (System.InvalidCastException iex) { throw new InvalidCastException("Array ('" + t.Name + "') could not be filled with value of type '" + type.Name + "'.", iex); } return(a); } if (!typeof(IList).IsAssignableFrom(t) || !(o is JavaScriptArray)) { throw new NotSupportedException(); } IList l = (IList)Activator.CreateInstance(t); MethodInfo mi = t.GetMethod("Add"); ParameterInfo pi = mi.GetParameters()[0]; for (int i = 0; i < list.Count; i++) { l.Add(JavaScriptDeserializer.Deserialize(list[i], pi.ParameterType)); } return(l); }
/// <summary> /// Converts an IJavaScriptObject into an NET object. /// </summary> /// <param name="o">The IJavaScriptObject object to convert.</param> /// <param name="t"></param> /// <returns>Returns a .NET object.</returns> public override object Deserialize(IJavaScriptObject o, Type t) { JavaScriptObject ht = o as JavaScriptObject; if (ht == null) { throw new NotSupportedException(); } if (!ht.Contains("keys") || !ht.Contains("values")) { throw new NotSupportedException(); } IDictionary d = (IDictionary)Activator.CreateInstance(t); ParameterInfo[] p = t.GetMethod("Add").GetParameters(); Type kT = p[0].ParameterType; Type vT = p[1].ParameterType; object key; object value; JavaScriptArray keys = ht["keys"] as JavaScriptArray; JavaScriptArray values = ht["values"] as JavaScriptArray; for (int i = 0; i < keys.Count && i < values.Count; i++) { key = JavaScriptDeserializer.Deserialize(keys[i], kT); value = JavaScriptDeserializer.Deserialize(values[i], vT); d.Add(key, value); } return(d); }
/// <summary> /// Converts an IJavaScriptObject into an NET object. /// </summary> /// <param name="o">The IJavaScriptObject object to convert.</param> /// <param name="t"></param> /// <returns>Returns a .NET object.</returns> public override object Deserialize(IJavaScriptObject o, Type t) { if (AjaxPro.Utility.Settings.OldStyle.Contains("renderJsonCompliant")) { return(new NotSupportedException("DataSets are not supported when renderJsonCompliant is configured.")); } JavaScriptObject ht = o as JavaScriptObject; if (ht == null) { throw new NotSupportedException(); } if (!ht.Contains("Tables") || !(ht["Tables"] is JavaScriptArray)) { throw new NotSupportedException(); } JavaScriptArray tables = (JavaScriptArray)ht["Tables"]; DataSet ds = new DataSet(); DataTable dt = null; foreach (IJavaScriptObject table in tables) { dt = (DataTable)JavaScriptDeserializer.Deserialize(table, typeof(DataTable)); if (dt != null) { ds.Tables.Add(dt); } } return(ds); }
/// <summary> /// Deserializes the custom object. /// </summary> /// <param name="o">The o.</param> /// <param name="type">The type.</param> /// <returns></returns> internal static object DeserializeCustomObject(JavaScriptObject o, Type type) { object c = Activator.CreateInstance(type); // TODO: is this a security problem? // if(o.GetType().GetCustomAttributes(typeof(AjaxClassAttribute), true).Length == 0) // throw new System.Security.SecurityException("Could not create class '" + type.FullName + "' because of missing AjaxClass attribute."); MemberInfo[] members = type.GetMembers(BindingFlags.GetField | BindingFlags.GetProperty | BindingFlags.Public | BindingFlags.Instance); foreach (MemberInfo memberInfo in members) { if (memberInfo.MemberType == MemberTypes.Field) { if (o.Contains(memberInfo.Name)) { FieldInfo fieldInfo = (FieldInfo)memberInfo; fieldInfo.SetValue(c, JavaScriptDeserializer.Deserialize((IJavaScriptObject)o[fieldInfo.Name], fieldInfo.FieldType)); } } else if (memberInfo.MemberType == MemberTypes.Property) { if (o.Contains(memberInfo.Name)) { PropertyInfo propertyInfo = (PropertyInfo)memberInfo; if (propertyInfo.CanWrite) { propertyInfo.SetValue(c, JavaScriptDeserializer.Deserialize((IJavaScriptObject)o[propertyInfo.Name], propertyInfo.PropertyType), new object[0]); } } } } return(c); }
/// <summary> /// Converts an IJavaScriptObject into an NET object. /// </summary> /// <param name="o">The IJavaScriptObject object to convert.</param> /// <param name="t"></param> /// <returns>Returns a .NET object.</returns> public override object Deserialize(IJavaScriptObject o, Type t) { JavaScriptObject ht = o as JavaScriptObject; if (o is JavaScriptSource) { // new Date(Date.UTC(2006,6,9,5,36,18,875)) string s = o.ToString(); if (s.StartsWith("new Date(Date.UTC(") && s.EndsWith("))")) { s = s.Substring(18, s.Length - 20); //Regex r = new Regex(@"(\d{4}),(\d{1,2}),(\d{1,2}),(\d{1,2}),(\d{1,2}),(\d{1,2}),(\d{1,3})", RegexOptions.Compiled); //Match m = r.Match(s); //if (m.Groups.Count != 8) // throw new NotSupportedException(); //int Year = int.Parse(m.Groups[1].Value); //int Month = int.Parse(m.Groups[2].Value) + 1; //int Day = int.Parse(m.Groups[3].Value); //int Hour = int.Parse(m.Groups[4].Value); //int Minute = int.Parse(m.Groups[5].Value); //int Second = int.Parse(m.Groups[6].Value); //int Millisecond = int.Parse(m.Groups[7].Value); //DateTime d = new DateTime(Year, Month, Day, Hour, Minute, Second, Millisecond); string[] p = s.Split(','); return(new DateTime(int.Parse(p[0]), int.Parse(p[1]) + 1, int.Parse(p[2]), int.Parse(p[3]), int.Parse(p[4]), int.Parse(p[5]), int.Parse(p[6])).AddMinutes(UtcOffsetMinutes)); } else if (s.StartsWith("new Date(") && s.EndsWith(")")) { long nanosecs = long.Parse(s.Substring(9, s.Length - 10)) * 10000; #if (NET20) nanosecs += new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).Ticks; DateTime d1 = new DateTime(nanosecs, DateTimeKind.Utc); #else nanosecs += new DateTime(1970, 1, 1, 0, 0, 0, 0).Ticks; DateTime d1 = new DateTime(nanosecs); #endif return(Utility.Settings.OldStyle.Contains("noUtcTime") ? d1 : d1.AddMinutes(UtcOffsetMinutes)); // TimeZone.CurrentTimeZone.GetUtcOffset(d1).TotalMinutes); } } else if (o is JavaScriptString) { #if (NET20) DateTime d2; if (DateTime.TryParseExact(o.ToString(), System.Globalization.DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AllowWhiteSpaces, out d2 ) == true) { return(Utility.Settings.OldStyle.Contains("noUtcTime") ? d2 : d2.AddMinutes(UtcOffsetMinutes)); // TimeZone.CurrentTimeZone.GetUtcOffset(d2).TotalMinutes); } #else try { DateTime d4 = DateTime.ParseExact(o.ToString(), System.Globalization.DateTimeFormatInfo.InvariantInfo.UniversalSortableDateTimePattern, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.AllowWhiteSpaces ); return(Utility.Settings.OldStyle.Contains("noUtcTime") ? d4 : d4.AddMinutes(UtcOffsetMinutes)); // TimeZone.CurrentTimeZone.GetUtcOffset(d4).TotalMinutes); } catch (FormatException) { } #endif } if (ht == null) { throw new NotSupportedException(); } int Year2 = (int)JavaScriptDeserializer.Deserialize(ht["Year"], typeof(int)); int Month2 = (int)JavaScriptDeserializer.Deserialize(ht["Month"], typeof(int)); int Day2 = (int)JavaScriptDeserializer.Deserialize(ht["Day"], typeof(int)); int Hour2 = (int)JavaScriptDeserializer.Deserialize(ht["Hour"], typeof(int)); int Minute2 = (int)JavaScriptDeserializer.Deserialize(ht["Minute"], typeof(int)); int Second2 = (int)JavaScriptDeserializer.Deserialize(ht["Second"], typeof(int)); int Millisecond2 = (int)JavaScriptDeserializer.Deserialize(ht["Millisecond"], typeof(int)); DateTime d5 = new DateTime(Year2, Month2, Day2, Hour2, Minute2, Second2, Millisecond2); return(Utility.Settings.OldStyle.Contains("noUtcTime") ? d5 : d5.AddMinutes(UtcOffsetMinutes)); // TimeZone.CurrentTimeZone.GetUtcOffset(d3).TotalMinutes); }
/// <summary> /// Retreives the parameters. /// </summary> /// <returns></returns> public override object[] RetreiveParameters() { context.Request.ContentEncoding = System.Text.UTF8Encoding.UTF8; ParameterInfo[] pi = method.GetParameters(); object[] args = new object[pi.Length]; // initialize default values for (int i = 0; i < pi.Length; i++) { args[i] = pi[i].DefaultValue; } byte[] b = new byte[context.Request.InputStream.Length]; if (context.Request.InputStream.Read(b, 0, b.Length) == 0) { return(null); } StreamReader sr = new StreamReader(new MemoryStream(b), System.Text.UTF8Encoding.UTF8); string v = null; try { v = sr.ReadToEnd(); } finally { sr.Close(); } // If something went wrong or there are no arguments // we can return with the empty argument array. if (v == null || pi.Length == 0 || v == "{}") { return(args); } hashCode = v.GetHashCode(); // check if we have to decrypt the JSON string. if (Utility.Settings != null && Utility.Settings.Security != null) { v = Utility.Settings.Security.SecurityProvider.Decrypt(v); } context.Items.Add(Constant.AjaxID + ".JSON", v); JavaScriptObject jso = (JavaScriptObject)JavaScriptDeserializer.DeserializeFromJson(v, typeof(JavaScriptObject)); for (int i = 0; i < pi.Length; i++) { if (jso.Contains(pi[i].Name)) { //if(pi[i].ParameterType.IsAssignableFrom(jso[pi[i].Name].GetType())) //{ // args[i] = jso[pi[i].Name]; //} //else { args[i] = JavaScriptDeserializer.Deserialize((IJavaScriptObject)jso[pi[i].Name], pi[i].ParameterType); } } } return(args); }