A DataTable Serializer for ASP.NET AJAX(转载)
此文转载自http://www.dennydotnet.com/post/2007/09/A-DataTable-Serializer-for-ASPNET-AJAX.aspx,未作翻译。
A DataTable Serializer for ASP.NET AJAX, implements JavaScriptConverter. Note that I did not implement a Deserialize method since I am using this for read only data.
A DataTable Serializer for ASP.NET AJAX, implements JavaScriptConverter. Note that I did not implement a Deserialize method since I am using this for read only data.
[code:c#]
![]() /// <summary>
/// <summary>
![]() /// DataTable to JSON converter
/// DataTable to JSON converter
![]() /// </summary>
/// </summary>
![]() public class JavaScriptDataTableConverter : JavaScriptConverter {
public class JavaScriptDataTableConverter : JavaScriptConverter {
![]() public override object Deserialize( IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer ) {
 public override object Deserialize( IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer ) {
![]() throw new NotImplementedException( "Deserialize is not implemented." );
  throw new NotImplementedException( "Deserialize is not implemented." );
![]() }
 } 
![]()
![]() public override IDictionary<string, object> Serialize( object obj, JavaScriptSerializer serializer ) {
 public override IDictionary<string, object> Serialize( object obj, JavaScriptSerializer serializer ) {
![]() DataTable dt = obj as DataTable;
  DataTable dt = obj as DataTable;
![]() Dictionary<string, object> result = new Dictionary<string, object>();
  Dictionary<string, object> result = new Dictionary<string, object>(); 
![]()
![]() if( dt != null && dt.Rows.Count > 0 ) {
  if( dt != null && dt.Rows.Count > 0 ) {
![]() // List for row values
   // List for row values
![]() List<object> rowValues = new List<object>();
   List<object> rowValues = new List<object>(); 
![]()
![]() foreach( DataRow dr in dt.Rows ) {
   foreach( DataRow dr in dt.Rows ) {
![]() // Dictionary for col name / col value
    // Dictionary for col name / col value
![]() Dictionary<string, object> colValues = new Dictionary<string, object>();
    Dictionary<string, object> colValues = new Dictionary<string, object>(); 
![]()
![]() foreach( DataColumn dc in dt.Columns ) {
    foreach( DataColumn dc in dt.Columns ) {
![]() colValues.Add( dc.ColumnName, // col name
     colValues.Add( dc.ColumnName, // col name
![]() ( string.Empty == dr[dc].ToString() ) ? null : dr[dc] ); // col value
      ( string.Empty == dr[dc].ToString() ) ? null : dr[dc] ); // col value
![]() }
    } 
![]()
![]() // Add values to row
    // Add values to row
![]() rowValues.Add( colValues );
    rowValues.Add( colValues );
![]() }
   } 
![]()
![]() // Add rows to serialized object
   // Add rows to serialized object
![]() result["rows"] = rowValues;
   result["rows"] = rowValues;
![]() }
  } 
![]()
![]() return result;
  return result;
![]() }
 } 
![]()
![]() public override IEnumerable<Type> SupportedTypes {
 public override IEnumerable<Type> SupportedTypes {
![]() //Define the DataTable as a supported type.
  //Define the DataTable as a supported type.
![]() get {
  get {
![]() return new System.Collections.ObjectModel.ReadOnlyCollection<Type>(
   return new System.Collections.ObjectModel.ReadOnlyCollection<Type>(
![]() new List<Type>(
    new List<Type>(
![]() new Type[] { typeof( DataTable ) }
     new Type[] { typeof( DataTable ) }
![]() )
    )
![]() );
   );
![]() }
  }
![]() }
 }
![]() }
}
![]()
![]() 
 /// <summary>
/// <summary> /// DataTable to JSON converter
/// DataTable to JSON converter /// </summary>
/// </summary> public class JavaScriptDataTableConverter : JavaScriptConverter {
public class JavaScriptDataTableConverter : JavaScriptConverter { public override object Deserialize( IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer ) {
 public override object Deserialize( IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer ) { throw new NotImplementedException( "Deserialize is not implemented." );
  throw new NotImplementedException( "Deserialize is not implemented." ); }
 } 
 public override IDictionary<string, object> Serialize( object obj, JavaScriptSerializer serializer ) {
 public override IDictionary<string, object> Serialize( object obj, JavaScriptSerializer serializer ) { DataTable dt = obj as DataTable;
  DataTable dt = obj as DataTable; Dictionary<string, object> result = new Dictionary<string, object>();
  Dictionary<string, object> result = new Dictionary<string, object>(); 
 if( dt != null && dt.Rows.Count > 0 ) {
  if( dt != null && dt.Rows.Count > 0 ) { // List for row values
   // List for row values List<object> rowValues = new List<object>();
   List<object> rowValues = new List<object>(); 
 foreach( DataRow dr in dt.Rows ) {
   foreach( DataRow dr in dt.Rows ) { // Dictionary for col name / col value
    // Dictionary for col name / col value Dictionary<string, object> colValues = new Dictionary<string, object>();
    Dictionary<string, object> colValues = new Dictionary<string, object>(); 
 foreach( DataColumn dc in dt.Columns ) {
    foreach( DataColumn dc in dt.Columns ) { colValues.Add( dc.ColumnName, // col name
     colValues.Add( dc.ColumnName, // col name ( string.Empty == dr[dc].ToString() ) ? null : dr[dc] ); // col value
      ( string.Empty == dr[dc].ToString() ) ? null : dr[dc] ); // col value }
    } 
 // Add values to row
    // Add values to row rowValues.Add( colValues );
    rowValues.Add( colValues ); }
   } 
 // Add rows to serialized object
   // Add rows to serialized object result["rows"] = rowValues;
   result["rows"] = rowValues; }
  } 
 return result;
  return result; }
 } 
 public override IEnumerable<Type> SupportedTypes {
 public override IEnumerable<Type> SupportedTypes { //Define the DataTable as a supported type.
  //Define the DataTable as a supported type. get {
  get { return new System.Collections.ObjectModel.ReadOnlyCollection<Type>(
   return new System.Collections.ObjectModel.ReadOnlyCollection<Type>( new List<Type>(
    new List<Type>( new Type[] { typeof( DataTable ) }
     new Type[] { typeof( DataTable ) } )
    ) );
   ); }
  } }
 } }
}

[/code]
And how do you implement this? In a web service...
[code:c#]
![]() using System.Web.Script.Serialization;
using System.Web.Script.Serialization; 
![]()
![]() //
// ![]() 
 
![]()
![]() [WebMethod()]
[WebMethod()]
![]() [ScriptMethod( ResponseFormat = ResponseFormat.Json )]
[ScriptMethod( ResponseFormat = ResponseFormat.Json )]
![]() public string TestJS( int Id ) {
public string TestJS( int Id ) {
![]() JavaScriptSerializer toJSON = new JavaScriptSerializer();
 JavaScriptSerializer toJSON = new JavaScriptSerializer();
![]() toJSON.RegisterConverters( new JavaScriptConverter[] { new JavaScriptDataTableConverter() } );
 toJSON.RegisterConverters( new JavaScriptConverter[] { new JavaScriptDataTableConverter() } ); 
![]()
![]() DataTable dt = new Query( Log.Schema )
 DataTable dt = new Query( Log.Schema )
![]() .WHERE( Log.Columns.ID, Id )
   .WHERE( Log.Columns.ID, Id )
![]() .ExecuteDataSet().Tables[0];
   .ExecuteDataSet().Tables[0]; 
![]()
![]() return toJSON.Serialize( dt );
 return toJSON.Serialize( dt );
![]() }
}
![]() 
[/code]
 using System.Web.Script.Serialization;
using System.Web.Script.Serialization; 
 //
//  
 
 [WebMethod()]
[WebMethod()] [ScriptMethod( ResponseFormat = ResponseFormat.Json )]
[ScriptMethod( ResponseFormat = ResponseFormat.Json )] public string TestJS( int Id ) {
public string TestJS( int Id ) { JavaScriptSerializer toJSON = new JavaScriptSerializer();
 JavaScriptSerializer toJSON = new JavaScriptSerializer(); toJSON.RegisterConverters( new JavaScriptConverter[] { new JavaScriptDataTableConverter() } );
 toJSON.RegisterConverters( new JavaScriptConverter[] { new JavaScriptDataTableConverter() } ); 
 DataTable dt = new Query( Log.Schema )
 DataTable dt = new Query( Log.Schema ) .WHERE( Log.Columns.ID, Id )
   .WHERE( Log.Columns.ID, Id ) .ExecuteDataSet().Tables[0];
   .ExecuteDataSet().Tables[0]; 
 return toJSON.Serialize( dt );
 return toJSON.Serialize( dt ); }
}
[/code]
That's all there is to it! Just deserialize to an object on the client-side and you're good to go!
Side Note: There is a DataTable serializer from Microsoft in the ASP.NET Futures package.
 
                    
                
 
  
                
            
         
 浙公网安备 33010602011771号
浙公网安备 33010602011771号