/// <summary> /// Outputs the data to the response stream /// </summary> public virtual void RenderOutput() { if (_url.ReturnType == RESTReturnType.xml) { _context.Response.ContentType = "text/xml"; _outputWriter.Write(_output); } else if (_url.ReturnType == RESTReturnType.json) { _context.Response.ContentType = "text/json"; XmlDocument xdoc = new XmlDocument(); xdoc.LoadXml(_output); //convert XML to a JSON string string json = XmlToJSONParser.XmlToJSON(xdoc); //clean up and prep for delivery json = json.Replace(@"\", @"\\"); //final clean up and make it safe json for client side _outputWriter.Write(XmlToJSONParser.SafeJSON(json)); } }
/// <summary> /// DataTable转换JSON DataTime类型列转换为String类型 /// </summary> /// <param name="Table"></param> /// <param name="TableName"></param> /// <param name="Sort"></param> /// <returns></returns> public static string ToJson(this DataTable Table, string Sort) { string Result = string.Empty; try { if (Table.Rows.Count <= 0) { throw new Exception(); } string XML = string.Empty; bool IsHasDatac = false; #region 检查是否存在日期格式 foreach (DataColumn Dc in Table.Columns) { if (Dc.DataType == typeof(System.DateTime)) { IsHasDatac = true; break; } } #endregion #region 生成XML if (IsHasDatac) { DataTable T = Table.Clone(); foreach (DataColumn Dc in T.Columns) { if (Dc.DataType == typeof(System.DateTime)) { Dc.DataType = typeof(String); } } T.Load(Table.CreateDataReader()); System.IO.StringWriter W = new System.IO.StringWriter(); if (!string.IsNullOrEmpty(Sort) && Table.Rows.Count > 0) { T.DefaultView.Sort = Sort; } T.TableName = T.TableName.IsNullOrEmpty() ? "Temp" : T.TableName; T.DefaultView.ToTable().WriteXml(W); XML = W.ToString(); W.Close(); W.Dispose(); T.Clear(); T.Dispose(); } else { System.IO.StringWriter W = new System.IO.StringWriter(); if (!string.IsNullOrEmpty(Sort) && Table.Rows.Count > 0) { Table.DefaultView.Sort = Sort; } Table.TableName = Table.TableName.IsNullOrEmpty() ? "Temp" : Table.TableName; Table.DefaultView.ToTable().WriteXml(W); XML = W.ToString(); W.Close(); W.Dispose(); } #endregion #region 替换 格式 XML = XML.Replace("<DocumentElement>", "<data>") .Replace("</DocumentElement>", "</data>") .Replace("<DocumentElement />", ""); XML = XML.Replace("<Table>", String.Concat("<rows>")).Replace("</Table>", String.Concat("</rows>")); System.Xml.XmlDocument XMLD = new System.Xml.XmlDocument(); XMLD.LoadXml(XML); Result = XmlToJSONParser.XmlToJSON(XMLD); Result = Result.Replace(@"\", @"\\"); #endregion } catch { } return(Result); }