convert from SqlDataReader to JSON

后端 未结 13 1198
忘掉有多难
忘掉有多难 2020-11-27 16:26
public string toJSON(SqlDataReader o)
{
    StringBuilder s = new StringBuilder();
    s.Append(\"[\");
    if (o.HasRows)
        while (o.Read())
            s.App         


        
13条回答
  •  感情败类
    2020-11-27 17:17

    Since SQL Server 2016, Microsoft embedded this feature with sql queries. You can achieve it by using FOR JSON keyword at the end of your queries.

    select * from table_example where somecolumn = somecondition FOR JSON AUTO
    

    for more details and example you can go through this official documents Format JSON Output Automatically with AUTO Mode (SQL Server)

    Here is the C# code example from Microsoft to get JSON string from SQL queries.

    var queryWithForJson = "SELECT ... FOR JSON";
    var conn = new SqlConnection("");
    var cmd = new SqlCommand(queryWithForJson, conn);
    conn.Open();
    var jsonResult = new StringBuilder();
    var reader = cmd.ExecuteReader();
    if (!reader.HasRows)
    {
        jsonResult.Append("[]");
    }
    else
    {
        while (reader.Read())
        {
            jsonResult.Append(reader.GetValue(0).ToString());
        }
    }
    

    Warning: This solution is only valid for SQL SERVER 2016 and higher.

提交回复
热议问题