2017-04-06 46 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 –