从SqlDataReader创建JSON字符串

Hri*_*sto 11 c# database asp.net json json.net

UPDATE

我想到了.看看我的答案如下.


我正在尝试创建一个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();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

问题是我不知道如何读取行中的每一列,SqlReader以便我可以调用WriteValue并给它正确的信息并将其附加到正确的列名.所以,如果一行看起来像这样......

| FirstName | LastName | Email |
Run Code Online (Sandbox Code Playgroud)

...我将如何JsonWriter为每个这样的行创建一个这样的行,使其包含行的所有列名和每列中的相应值,然后使用它JsonWriter来构建一个准备好通过HTTP响应返回的JSON字符串?

如果我需要澄清任何事情,请告诉我.

Pro*_*ega 21

我的版本:

这不使用DataSchema并将结果包装在数组中,而不是每行使用一个writer.

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();
}
Run Code Online (Sandbox Code Playgroud)


Cod*_*ick 6

编辑具体例子:

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();
Run Code Online (Sandbox Code Playgroud)


Hri*_*sto 4

知道了!这是 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);
Run Code Online (Sandbox Code Playgroud)

...所以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
    }
});
Run Code Online (Sandbox Code Playgroud)

感谢斯科特的回答,这启发了我找到解决方案。

赫里斯托