从SqlDataReader创建JSON字符串

本文关键字:字符串 JSON 创建 SqlDataReader | 更新日期: 2023-09-27 17:49:19

更新

我想明白了。看看下面我的答案。


我正在尝试创建一个JSON字符串,表示数据库表中的一行,以便在HTTP响应中返回。看起来像Json。NET将是一个很好的利用工具。但是,我不知道如何在从数据库中读取时构建JSON字符串

问题的标志是令人讨厌的评论/******** ********/

// connect to DB
theSqlConnection.Open(); // open the connection
SqlDataReader reader = sqlCommand.ExecuteReader();
if (reader.HasRows) {
    while(reader.Read()) {
        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);
        using (JsonWriter jsonWriter = new JsonTextWriter(sw)) {
            // read columns from the current row and build this JsonWriter
            jsonWriter.WriteStartObject();
            jsonWriter.WritePropertyName("FirstName");
            // I need to read the value from the database
/******** I can't just say reader[i] to get the ith column. How would I loop here to get all columns? ********/
            jsonWriter.WriteValue(... ? ...);
            jsonWriter.WritePropertyName("LastName");
            jsonWriter.WriteValue(... ? ...);
            jsonWriter.WritePropertyName("Email");
            jsonWriter.WriteValue(... ? ...);
            // etc...
            jsonWriter.WriteEndObject();
        }
    }
}

问题是,我不知道如何从SqlReader中读取行中的每一列,这样我就可以调用WriteValue并为其提供正确的信息,并将其附加到正确的列名上。所以如果一排像这样。。。

| FirstName | LastName | Email |

如何为每一行创建一个JsonWriter,使其包含该行的所有列名和每列中的相应值,然后使用该JsonWriter构建一个JSON字符串,该字符串可以通过HTTP响应返回?

如果我需要澄清什么,请告诉我。

从SqlDataReader创建JSON字符串

我的版本:

这不使用DataSchema,还将结果封装在一个数组中,而不是每行使用一个编写器。

SqlDataReader rdr = cmd.ExecuteReader();
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);    
using (JsonWriter jsonWriter = new JsonTextWriter(sw)) 
{    
    jsonWriter.WriteStartArray();
    while (rdr.Read())
    {
        jsonWriter.WriteStartObject();
        int fields = rdr.FieldCount;
        for (int i = 0; i < fields; i++)
        { 
            jsonWriter.WritePropertyName(rdr.GetName(i));
            jsonWriter.WriteValue(rdr[i]);
        }
        jsonWriter.WriteEndObject();
    }
    jsonWriter.WriteEndArray();
}

为特定示例编辑:

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();

明白了!这是C#。。。

// ... SQL connection and command set up, only querying 1 row from the table
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
JsonWriter jsonWriter = new JsonTextWriter(sw);
try {
    theSqlConnection.Open(); // open the connection
    // read the row from the table
    SqlDataReader reader = sqlCommand.ExecuteReader();
    reader.Read();
    int fieldcount = reader.FieldCount; // count how many columns are in the row
    object[] values = new object[fieldcount]; // storage for column values
    reader.GetValues(values); // extract the values in each column
    jsonWriter.WriteStartObject();
    for (int index = 0; index < fieldcount; index++) { // iterate through all columns
        jsonWriter.WritePropertyName(reader.GetName(index)); // column name
        jsonWriter.WriteValue(values[index]); // value in column
    }
    jsonWriter.WriteEndObject();
    reader.Close();
} catch (SqlException sqlException) { // exception
    context.Response.ContentType = "text/plain";
    context.Response.Write("Connection Exception: ");
    context.Response.Write(sqlException.ToString() + "'n");
} finally {
    theSqlConnection.Close(); // close the connection
}
// END of method
// the above method returns sb and another uses it to return as HTTP Response...
StringBuilder theTicket = getInfo(context, ticketID);
context.Response.ContentType = "application/json";
context.Response.Write(theTicket);

所以StringBuilder sb变量是JSON对象,它表示我想要查询的行。这是JavaScript。。。

$.ajax({
    type: 'GET',
    url: 'Preview.ashx',
    data: 'ticketID=' + ticketID,
    dataType: "json",
    success: function (data) {
        // data is the JSON object the server spits out
        // do stuff with the data
    }
});

感谢Scott的回答,这激发了我找到解决方案的灵感。

Hristo

我制作了以下方法,它将任何DataReader转换为JSON,但仅用于单深度序列化:

您应该将读取器和列名作为字符串数组传递,例如:

String [] columns = {"CustomerID", "CustomerName", "CustomerDOB"};

然后调用方法

public static String json_encode(IDataReader reader, String[] columns)
    {
        int length = columns.Length;
        String res = "{";
        while (reader.Read())
        {
            res += "{";
            for (int i = 0; i < length; i++)
            {
                res += "'"" + columns[i] + "'":'"" + reader[columns[i]].ToString() + "'"";
                if (i < length - 1)
                    res += ",";
            }
            res += "}";
        }
        res += "}";
        return res;
    }