Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create JSON string from SqlDataReader

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 response. It seems like Json.NET would be a good tool to utilize. However, I'm not sure how to do build the JSON string while I'm reading from the database.

The problem is marked by the obnoxious comments /******** ********/

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

The problem is that I don't know how to read each column from the row from the SqlReader such that I can call WriteValue and give it the correct information and attach it to the correct column name. So if a row looks like this...

| FirstName | LastName | Email |

... how would I create a JsonWriter for each such row such that it contains all column names of the row and the corresponding values in each column and then use that JsonWriter to build a JSON string that is ready for returning through an HTTP Response?

Let me know if I need to clarify anything.

like image 481
Hristo Avatar asked Apr 05 '11 15:04

Hristo


3 Answers

My version:

This doesn't use DataSchema and also wraps the results in an array, instead of using a writer per row.

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();
}
like image 187
ProVega Avatar answered Oct 07 '22 20:10

ProVega


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();
like image 24
Code Maverick Avatar answered Oct 07 '22 21:10

Code Maverick


Got it! Here's the 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);

... so the StringBuilder sb variable is the JSON object that represents the row I wanted to query. Here is the 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
    }
});

Thanks to Scott for his answer which inspired me to come to my solution.

Hristo

like image 34
Hristo Avatar answered Oct 07 '22 19:10

Hristo