2017-04-06 45 views
0

我不得不數據庫建立的連接如何從數據庫獲取json類型的響應?

public string Respond(string sqlExpression) 
{   
    string connectionString = @"Data Source=***;Initial Catalog=***; 
    User Id=***;Password=***;"; 
    var kek = new List<List<string>>(); 
    using (SqlConnection connection = new SqlConnection(connectionString)) 
    { 
     connection.Open(); 
     SqlCommand command = new SqlCommand(sqlExpression, connection); 
     var reader = command.ExecuteReader(); 
     if (reader.HasRows) 
     { 
      while (reader.Read()) 
      { 
       var a = new List<string>(); 
       for (int i = 0; i < reader.FieldCount; i++) 
       { 
        a.Add(reader.GetSqlString(i).ToString()); 
       } 
       kek.Add(a); 
      } 
     } 
     reader.Close(); 
    } 
    return kek.ToJSON(); 
} 

這是該查詢返回:database table 我從這種方法得到的,是這樣的:json file

基本上,這是一個JSON至極包含外部「 []「,裏面有一個」[]「,其中有字段數據。雖然我想要的是獲得字段名稱(「名稱」,「簡介」,「細節」)和數據的JSON文件。 如何在不生成類的情況下執行此操作?

+1

有什麼問題產生的類? –

回答

0

您應該使用System.Web.Script.Serialization.JavaScriptSerializer命名空間。您必須從數據庫表中收集數據表。在那之後,你可以用下面的命名空間轉換成json;

public string ConvertDataTableToJson() 
{ 
    DataTable dt = new DataTable(); 
    using (SqlConnection con = new SqlConnectionc(connectionString) 
    { 
     using (SqlCommand cmd = new SqlCommand(sqlExpression, con)) 
     { 
      con.Open(); 
      SqlDataAdapter da = new SqlDataAdapter(cmd); 
      da.Fill(dt); 
      System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer(); 
      List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>(); 
      Dictionary<string, object> row; 
      foreach (DataRow dr in dt.Rows) 
      { 
       row = new Dictionary<string, object>(); 
       foreach (DataColumn col in dt.Columns) 
       { 
        row.Add(col.ColumnName, dr[col]); 
       } 
       rows.Add(row); 
      } 
      return serializer.Serialize(rows); 
     } 
    } 
} 

在最後,你會得到這樣的事情

{"records":[ 
{ 
"Id": 1, 
"Name": "Foo", 
"Surname": "Bar" 
} 
]} 
+1

我不推薦JavaScriptSerializer ......它很慢,它不能很好地處理邊緣情況,它不是行業標準。有很多很棒的序列化器,比如Json.Net或Jil。 –

+0

@DavidL我沒有測試速度。性能測試我的問題較小。如果你有一個關於它的性能比較,這將是偉大的 –

+1

當然:http://www.newtonsoft.com/json/help/html/JsonNetVsDotNetSerializers.htm –