create JSON string from SqlDataReader

前端 未结 4 1967
予麋鹿
予麋鹿 2021-02-08 03:55

UPDATE

I figured it out. Check out my answer below.


I\'m trying to create a JSON string representing a row from a database table to return in an HTTP res

4条回答
  •  [愿得一人]
    2021-02-08 04:28

    EDITED FOR SPECIFIC EXAMPLE:

    theSqlConnection.Open();
    
    SqlDataReader reader = sqlCommand.ExecuteReader();
    DataTable schemaTable = reader.GetSchemaTable();
    
    foreach (DataRow row in schemaTable.Rows)
    {
        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);
    
        using (JsonWriter jsonWriter = new JsonTextWriter(sw)) 
        {    
            jsonWriter.WriteStartObject();
    
            foreach (DataColumn column in schemaTable.Columns)
            {
                jsonWriter.WritePropertyName(column.ColumnName);
                jsonWriter.WriteValue(row[column]);
            }
    
            jsonWriter.WriteEndObject();
        }
    }
    
    theSqlConnection.Close();
    

提交回复
热议问题