code_junkie

DataTable to JSON

Nov 13th, 2011
115
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.57 KB | None | 0 0
  1. public static class JSONHelper
  2. {
  3. public static string FromDataTable(DataTable dt)
  4. {
  5. string rowDelimiter = "";
  6.  
  7. StringBuilder result = new StringBuilder("[");
  8. foreach (DataRow row in dt.Rows)
  9. {
  10. result.Append(rowDelimiter);
  11. result.Append(FromDataRow(row));
  12. rowDelimiter = ",";
  13. }
  14. result.Append("]");
  15.  
  16. return result.ToString();
  17. }
  18.  
  19. public static string FromDataRow(DataRow row)
  20. {
  21. DataColumnCollection cols = row.Table.Columns;
  22. string colDelimiter = "";
  23.  
  24. StringBuilder result = new StringBuilder("{");
  25. for (int i = 0; i < cols.Count; i++)
  26. { // use index rather than foreach, so we can use the index for both the row and cols collection
  27. result.Append(colDelimiter).Append(""")
  28. .Append(cols[i].ColumnName).Append("":")
  29. .Append(JSONValueFromDataRowObject(row[i], cols[i].DataType));
  30.  
  31. colDelimiter = ",";
  32. }
  33. result.Append("}");
  34. return result.ToString();
  35. }
  36.  
  37. // possible types:
  38. // http://msdn.microsoft.com/en-us/library/system.data.datacolumn.datatype(VS.80).aspx
  39. private static Type[] numeric = new Type[] {typeof(byte), typeof(decimal), typeof(double),
  40. typeof(Int16), typeof(Int32), typeof(SByte), typeof(Single),
  41. typeof(UInt16), typeof(UInt32), typeof(UInt64)};
  42.  
  43. // I don't want to rebuild this value for every date cell in the table
  44. private static long EpochTicks = new DateTime(1970, 1, 1).Ticks;
  45.  
  46. private static string JSONValueFromDataRowObject(object value, Type DataType)
  47. {
  48. // null
  49. if (value == DBNull.Value) return "null";
  50.  
  51. // numeric
  52. if (Array.IndexOf(numeric, DataType) > -1)
  53. return value.ToString(); // TODO: eventually want to use a stricter format
  54.  
  55. // boolean
  56. if (DataType == typeof(bool))
  57. return ((bool)value) ? "true" : "false";
  58.  
  59. // date -- see http://weblogs.asp.net/bleroy/archive/2008/01/18/dates-and-json.aspx
  60. if (DataType == typeof(DateTime))
  61. return ""\/Date(" + new TimeSpan(((DateTime)value).ToUniversalTime().Ticks - EpochTicks).TotalMilliseconds.ToString() + ")\/"";
  62.  
  63. // TODO: add Timespan support
  64. // TODO: add Byte[] support
  65.  
  66. //TODO: this would be _much_ faster with a state machine
  67. // string/char
  68. return """ + value.ToString().Replace(@"", @"\").Replace(Environment.NewLine, @"n").Replace(""", @"""") + """;
  69. }
  70. }
Add Comment
Please, Sign In to add comment