2009-01-16 79 views
19

我最近需要将数据表序列化为JSON。我在哪里,我们仍然在.Net 2.0,所以我不能在.Net 3.5中使用JSON序列化程序。我觉得这一定是以前做过的,所以我去网上查了一下found一个numberdifferentoptions。其中一些取决于一个额外的图书馆,我会很难通过这里。其他需要先转换为List<Dictionary<>>,这似乎有点尴尬和不必要。另一个处理所有的值像一个字符串。由于某种原因,我无法真正支持其中的任何一个,所以我决定推出自己的,这是张贴在下面。DataTable to JSON

正如您从阅读//TODO评论可以看到的,它在一些地方是不完整的。这段代码已经在制作中,所以它在基本意义上“起作用”。不完整的地方是我们知道我们的生产数据当前不会触及它的地方(数据库中没有时间片或字节数组)。我在这里发布的原因是,我觉得这可能会更好一点,我希望帮助完成和改进此代码。任何输入欢迎。

请注意,此功能内置于.Net 3.5及更高版本,因此今天使用此代码的唯一原因是如果您仍仅限于.Net 2.0。即使如此,JSON.Net已经成为这类事情的goto库。

public static class JSONHelper 
{ 
    public static string FromDataTable(DataTable dt) 
    { 
     string rowDelimiter = ""; 

     StringBuilder result = new StringBuilder("["); 
     foreach (DataRow row in dt.Rows) 
     { 
      result.Append(rowDelimiter); 
      result.Append(FromDataRow(row)); 
      rowDelimiter = ","; 
     } 
     result.Append("]"); 

     return result.ToString(); 
    } 

    public static string FromDataRow(DataRow row) 
    { 
     DataColumnCollection cols = row.Table.Columns; 
     string colDelimiter = ""; 

     StringBuilder result = new StringBuilder("{");  
     for (int i = 0; i < cols.Count; i++) 
     { // use index rather than foreach, so we can use the index for both the row and cols collection 
      result.Append(colDelimiter).Append("\"") 
        .Append(cols[i].ColumnName).Append("\":") 
        .Append(JSONValueFromDataRowObject(row[i], cols[i].DataType)); 

      colDelimiter = ","; 
     } 
     result.Append("}"); 
     return result.ToString(); 
    } 

    // possible types: 
    // http://msdn.microsoft.com/en-us/library/system.data.datacolumn.datatype(VS.80).aspx 
    private static Type[] numeric = new Type[] {typeof(byte), typeof(decimal), typeof(double), 
            typeof(Int16), typeof(Int32), typeof(SByte), typeof(Single), 
            typeof(UInt16), typeof(UInt32), typeof(UInt64)}; 

    // I don't want to rebuild this value for every date cell in the table 
    private static long EpochTicks = new DateTime(1970, 1, 1).Ticks; 

    private static string JSONValueFromDataRowObject(object value, Type DataType) 
    { 
     // null 
     if (value == DBNull.Value) return "null"; 

     // numeric 
     if (Array.IndexOf(numeric, DataType) > -1) 
      return value.ToString(); // TODO: eventually want to use a stricter format. Specifically: separate integral types from floating types and use the "R" (round-trip) format specifier 

     // boolean 
     if (DataType == typeof(bool)) 
      return ((bool)value) ? "true" : "false"; 

     // date -- see http://weblogs.asp.net/bleroy/archive/2008/01/18/dates-and-json.aspx 
     if (DataType == typeof(DateTime))  
      return "\"\\/Date(" + new TimeSpan(((DateTime)value).ToUniversalTime().Ticks - EpochTicks).TotalMilliseconds.ToString() + ")\\/\""; 

     // TODO: add Timespan support 
     // TODO: add Byte[] support 

     //TODO: this would be _much_ faster with a state machine 
     //TODO: way to select between double or single quote literal encoding 
     //TODO: account for database strings that may have single \r or \n line breaks 
     // string/char 
     return "\"" + value.ToString().Replace(@"\", @"\\").Replace(Environment.NewLine, @"\n").Replace("\"", @"\""") + "\""; 
    } 
} 

更新:
这是现在老了,但我想指出一些关于这个代码是如何处理日期。我使用的格式在当时是有意义的,因为网址中的确切原因。然而,这个理由包括以下内容:

老实说,JSON模式通过使字符串作为日期文字“子类型”来解决问题,但这仍然在进行中,它会在达成任何重要的采纳之前需要时间。

那么,时间已经过去了。今天,只需使用ISO 8601日期格式即可。我不打算改变代码,因为真的:这是古老的。只要去使用JSON.Net。

+0

如果今天有人问到这个问题,它会代替代码审查堆栈交换。我已经将其标记为在那里移动,但它引起我注意的唯一原因是它只是获得了“着名问题”黄金徽章。在迁移中会失去这种观点。 – 2012-05-08 14:18:45

+0

我认为这将太旧以至于无法迁移。如果你还可以,它可以住在这里? – Kev 2012-05-08 22:48:21

+0

我不介意,只是想着最合适的方式。我有其他旧东西移动。 – 2012-05-09 03:01:01

回答