Esempio n. 1
0
 //public T Deserialize<T>(string json)
 //{
 //    T obj = Activator.CreateInstance<T>();
 //    using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(json)))
 //    {
 //        DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType());
 //        return (T)serializer.ReadObject(ms);
 //    }
 //}
 /// <summary>
 /// 将从数据库里查询出的表格Json字符转换成datatable
 /// </summary>
 /// <param name="json"></param>
 /// <returns></returns>
 public static System.Data.DataTable Json2DataTable(string json)
 {
     try
     {
         AjaxPro.JavaScriptArray arrayS =
             AjaxPro.JavaScriptDeserializer.DeserializeFromJson <AjaxPro.JavaScriptArray>(json);
         System.Data.DataTable dt = new System.Data.DataTable();
         bool isInitDt            = false;
         foreach (JavaScriptObject item in arrayS)
         {
             if (!isInitDt)
             {
                 foreach (string key in item.Keys)
                 {
                     System.Data.DataColumn fNameColumn = new System.Data.DataColumn();
                     fNameColumn.DataType     = System.Type.GetType("System.String");
                     fNameColumn.ColumnName   = key;
                     fNameColumn.DefaultValue = "";
                     dt.Columns.Add(fNameColumn);
                 }
                 isInitDt = true;
             }
             System.Data.DataRow dr = dt.NewRow();
             foreach (string key in item.Keys)
             {
                 //dr[key] = item[key].Value;
                 dr[key] = item[key].Value.Trim('\"');
             }
             dt.Rows.Add(dr);
         }
         return(dt);
     }
     catch (Exception ex)
     {
         Debug.WriteLine(ex.Message);
         return(null);
     }
 }
Esempio n. 2
0
        /// <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);
        }
Esempio n. 3
0
        /// <summary>
        /// Converts an XML document to an IJavaScriptObject (JSON).
        /// <see cref="http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html?page=1">Stefan Goessner</see>
        ///     <see cref="http://developer.yahoo.com/common/json.html#xml">Yahoo XML JSON</see>
        /// </summary>
        /// <param name="n">The XmlNode to serialize to JSON.</param>
        /// <returns>A IJavaScriptObject.</returns>
        public static IJavaScriptObject GetIJavaScriptObjectFromXmlNode(XmlNode n)
        {
            if (n == null)
            {
                return(null);
            }

            //if (xpath == "" || xpath == "/")
            //    xpath = n.Name;

            System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"\w+|\W+", System.Text.RegularExpressions.RegexOptions.Compiled);
            JavaScriptObject o = new JavaScriptObject();

            if (n.NodeType == XmlNodeType.Element)
            {
                for (int i = 0; i < n.Attributes.Count; i++)
                {
                    o.Add("@" + n.Attributes[i].Name, new JavaScriptString(n.Attributes[i].Value));
                }

                if (n.FirstChild != null)                       // element has child nodes
                {
                    int  textChild       = 0;
                    bool hasElementChild = false;

                    for (XmlNode e = n.FirstChild; e != null; e = e.NextSibling)
                    {
                        if (e.NodeType == XmlNodeType.Element)
                        {
                            hasElementChild = true;
                        }
                        if (e.NodeType == XmlNodeType.Text && r.IsMatch(e.InnerText))
                        {
                            textChild++;                                                                                        // non-whitespace text
                        }
                    }

                    if (hasElementChild)
                    {
                        if (textChild < 2)                              // structured element with evtl. a single text node
                        {
                            for (XmlNode e = n.FirstChild; e != null; e = e.NextSibling)
                            {
                                if (e.NodeType == XmlNodeType.Text)
                                {
                                    o.Add("#text", new JavaScriptString(e.InnerText));
                                }
                                else if (o.Contains(e.Name))
                                {
                                    if (o[e.Name] is JavaScriptArray)
                                    {
                                        ((JavaScriptArray)o[e.Name]).Add(GetIJavaScriptObjectFromXmlNode(e));
                                    }
                                    else
                                    {
                                        IJavaScriptObject _o = o[e.Name];
                                        JavaScriptArray   a  = new JavaScriptArray();
                                        a.Add(_o);
                                        a.Add(GetIJavaScriptObjectFromXmlNode(e));
                                        o[e.Name] = a;
                                    }
                                }
                                else
                                {
                                    o.Add(e.Name, GetIJavaScriptObjectFromXmlNode(e));
                                }
                            }
                        }
                    }
                    else if (textChild > 0)
                    {
                        if (n.Attributes.Count == 0)
                        {
                            return(new JavaScriptString(n.InnerText));
                        }
                        else
                        {
                            o.Add("#text", new JavaScriptString(n.InnerText));
                        }
                    }
                }
                if (n.Attributes.Count == 0 && n.FirstChild == null)
                {
                    return(new JavaScriptString(n.InnerText));
                }
            }
            else if (n.NodeType == XmlNodeType.Document)
            {
                return(GetIJavaScriptObjectFromXmlNode(((XmlDocument)n).DocumentElement));
            }
            else
            {
                throw new NotSupportedException("Unhandled node type '" + n.NodeType + "'.");
            }

            return(o);
        }
		/// <summary>
		/// Converts an XML document to an IJavaScriptObject (JSON).
		/// <see cref="http://www.xml.com/pub/a/2006/05/31/converting-between-xml-and-json.html?page=1">Stefan Goessner</see>
		/// 	<see cref="http://developer.yahoo.com/common/json.html#xml">Yahoo XML JSON</see>
		/// </summary>
		/// <param name="n">The XmlNode to serialize to JSON.</param>
		/// <returns>A IJavaScriptObject.</returns>
		public static IJavaScriptObject GetIJavaScriptObjectFromXmlNode(XmlNode n)
		{
			if (n == null)
				return null;

			//if (xpath == "" || xpath == "/")
			//    xpath = n.Name;

			System.Text.RegularExpressions.Regex r = new System.Text.RegularExpressions.Regex(@"\w+|\W+", System.Text.RegularExpressions.RegexOptions.Compiled);
			JavaScriptObject o = new JavaScriptObject();

			if (n.NodeType == XmlNodeType.Element)
			{
				for (int i = 0; i < n.Attributes.Count; i++)
				{
					o.Add("@" + n.Attributes[i].Name, new JavaScriptString(n.Attributes[i].Value));
				}

				if (n.FirstChild != null)	// element has child nodes
				{
					int textChild = 0;
					bool hasElementChild = false;

					for (XmlNode e = n.FirstChild; e != null; e = e.NextSibling)
					{
						if (e.NodeType == XmlNodeType.Element) hasElementChild = true;
						if (e.NodeType == XmlNodeType.Text && r.IsMatch(e.InnerText)) textChild++;	// non-whitespace text
					}

					if (hasElementChild)
					{
						if (textChild < 2)	// structured element with evtl. a single text node
						{
							for (XmlNode e = n.FirstChild; e != null; e = e.NextSibling)
							{
								if (e.NodeType == XmlNodeType.Text)
								{
									o.Add("#text", new JavaScriptString(e.InnerText));
								}
								else if (o.Contains(e.Name))
								{
									if (o[e.Name] is JavaScriptArray)
									{
										((JavaScriptArray)o[e.Name]).Add(GetIJavaScriptObjectFromXmlNode(e));
									}
									else
									{
										IJavaScriptObject _o = o[e.Name];
										JavaScriptArray a = new JavaScriptArray();
										a.Add(_o);
										a.Add(GetIJavaScriptObjectFromXmlNode(e));
										o[e.Name] = a;
									}
								}
								else
								{
									o.Add(e.Name, GetIJavaScriptObjectFromXmlNode(e));
								}
							}
						}
					}
					else if (textChild > 0)
					{
						if (n.Attributes.Count == 0)
							return new JavaScriptString(n.InnerText);
						else
							o.Add("#text", new JavaScriptString(n.InnerText));
					}
				}
				if (n.Attributes.Count == 0 && n.FirstChild == null)
					return new JavaScriptString(n.InnerText);
			}
			else if (n.NodeType == XmlNodeType.Document)
				return GetIJavaScriptObjectFromXmlNode(((XmlDocument)n).DocumentElement);
			else
				throw new NotSupportedException("Unhandled node type '" + n.NodeType + "'.");

			return o;
		}
		/// <summary>
		/// Deserialzes from ajax XML.
		/// </summary>
		/// <param name="n">The n.</param>
		/// <returns></returns>
		internal static IJavaScriptObject DeserialzeFromAjaxXml(XmlNode n)
		{
			switch (n.Name)
			{
				case "array":

					JavaScriptArray a = new JavaScriptArray();

					foreach (XmlNode item in n.ChildNodes)
						a.Add(DeserialzeFromAjaxXml(item));

					return a;

				case "boolean":

					JavaScriptBoolean b = new JavaScriptBoolean(n.InnerText == "true");
					return b;

				case "number":

					JavaScriptNumber i = new JavaScriptNumber();
					i.Append(n.InnerText);

					return i;

				case "string":

					JavaScriptString s = new JavaScriptString();
					s.Append(n.InnerText);

					return s;

				case "object":

					JavaScriptObject o = new JavaScriptObject();

					foreach (XmlNode p in n.SelectNodes("property"))
					{
						if (p.Attributes["name"] == null || p.ChildNodes.Count != 1)
							continue;

						o.Add(p.Attributes["name"].Value, DeserialzeFromAjaxXml(p.ChildNodes[0]));
					}

					return o;
			}

			return null;
		}
        /// <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);
                JavaScriptDeserializer.ThrowExceptionIfNotCustomTypeDeserializationAllowed(colType);

                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);
        }
Esempio n. 7
0
        /// <summary>
        /// Read an array object from the JSON string.
        /// </summary>
        /// <returns>Returns an ArrayList with all objects.</returns>
		internal JavaScriptArray ReadArray()
		{
			JavaScriptArray a = new JavaScriptArray();

			if (_ch == JSON_ARRAY_BEGIN)
			{
				ReadNext();
				ReadWhiteSpaces();

				if (_ch == JSON_ARRAY_END)
				{
					ReadNext();
					return a;
				}

				while (_ch != END_OF_STRING)
				{
					a.Add(GetObject());
					ReadWhiteSpaces();

					if (_ch == JSON_ARRAY_END)
					{
						ReadNext();
						return a;
					}
					else if (_ch != JSON_ITEMS_SEPARATOR)
					{
						break;
					}
					ReadNext();
					ReadWhiteSpaces();
				}
			}
			else
			{
				throw new NotSupportedException("Array could not be read.");
			}

			return a;
		}